Hi, I would like to make a “Load More” button but I can’t make it work with my blog and to be honest I don’t really understand how it work, so there is “blog” (parent) and “blogarticle” (child).
template/blog.php*
<div class"main">
<div class="articles" data-page="<?= $page->url() ?>" data-limit="<?= $limit ?>">
<!-- Loop through the projects -->
<?php foreach($page as $article): ?>
<?php snippet('homearticle', compact('homearticle')) ?>
<?php endforeach ?>
</div>
<button class="load-more">Load more</button>
</div>
template/blog.json.php*
<?php
$html = '';
foreach($page as $article) {
// reuse the project snippet to create the HTML for each project
// we need to set the third parameter to true, to return the
// snippet content instead of echoing it
$html .= snippet('homearticle', compact('homearticle'), true);
}
// add $html and $more to the $data array
$data['html'] = $html;
$data['more'] = $more;
// JSON encode the $data array
echo json_encode($data);
?>
snippets/homearticle.php*
<div class="HomeArticle">
<a href="<?= $article->url() ?>"><?= $article->title() ?></a>
<!--always check if the image exists!-->
<?php if($coverimage = $article->coverImage()->toFile()): ?>
<a href="<?= $article->url() ?>"><img src="<?= $coverimage->url() ?>"></a>
<?php endif ?>
</div>
controllers/blog.php*
<?php
return function($site, $pages, $page) {
$article = $page->children()->visible()->filterBy('template', '==', 'blogarticle')->unscheduled();
$count = $article->count();
// check if the request is an Ajax request and if the limit and offset keys are set
if(r::ajax() && get('offset') && get('limit')) {
// convert limit and offset values to integer
$offset = intval(get('offset'));
$limit = intval(get('limit'));
// limit projects using offset and limit values
$page = $article->offset($offset)->limit($limit);
// check if there are more projects left
$more = $count > $offset + $limit;
// otherwise set the number of projects initially displayed
} else {
$offset = 0;
$limit = 2;
$projects = $article->limit($limit);
}
return compact('offset', 'limit', 'article', 'more');
};
?>
assets/js/script.js*
$(function(){
var element = $('.page');
var url = element.data('page') + '.json';
var limit = parseInt(element.data('limit'));
var offset = limit;
$('.load-more').on('click', function(e) {
$.get(url, {limit: limit, offset: offset}, function(data) {
if(data.more === false) {
$('.load-more').hide();
}
element.children().last().after(data.html);
offset += limit;
});
});
});
So if I understand, it will load the snippet that will add 2 more article in the div class=“articles”, but if we use limit instead of pagination, can we make the button load more disapear if there is no more article to load ? We can’t check if there are next page …
Thanks