Hi everybody
Sorry in advance for the X time this question was asked…
But I really can’t make working the tutorial from the cookbook about the AJAX LOAD MORE
In my case, I want to make it on my homepage. For now, I’m getting an error on $data['more'] = $more;
into http://mysite/.json (the json of the homepage). This is my code :
HOME.PHP (template)
<main>
<section class="gallery projects" id="lightgallery" data-page="<?= $page->url() ?>" data-limit="<?= $limit ?>">
<?php foreach($site->find('projets')->children()->visible()->sortBy('sort', 'asc') as $projet): ?>
<?php snippet('projet', compact('projet')) ?>
<?php endforeach ?>
</section>
<button class="load-more">Load more</button>
</main>
HOME.PHP (controller)
<?php
return function($site, $pages, $page) {
$projects = $site->find('projets')->children()->visible()->sortBy('sort', 'asc');
$count = $projects->count();
if(r::ajax() && get('offset') && get('limit')) {
$offset = intval(get('offset'));
$limit = intval(get('limit'));
$projects = $projects->offset($offset)->limit($limit);
$more = $count > $offset + 1;
} else {
$offset = 0;
$limit = 2;
$projects = $projects->limit($limit);
}
return compact('offset', 'limit', 'projects', 'more');
};
HOME.JSON.PHP
<?php
$html = '';
foreach($site->find('projets')->children()->visible()->sortBy('sort', 'asc') as $projet) {
$html .= snippet('projet', compact('projet'), true);
}
$data['html'] = $html;
$data['more'] = $more;
echo json_encode($data);
PROJECT.PHP (snippet)
<?php foreach($site->find('projets')->children()->visible()->sortBy('sort', 'asc')->images()->sortBy('sort', 'asc') as $image): ?>
<article class="project">
<figure>
<a class="link" data-download-url="false" data-sub-html=".caption" href="<?php echo $image->url() ?>" data-srcset="<?php echo $image->resize(375)->url() ?> 375w, <?php echo $image->resize(480)->url() ?> 480w, <?php echo $image->resize(757)->url() ?> 757w, <?php echo $image->resize(1920)->url() ?> 1920w" data-sizes="(min-width: 40em) 80vw, 100vw">
<img alt="<?php echo $site->find('projets')->children()->visible()->sortBy('sort', 'asc')->title() ?>-Olivier-Jonvaux" class="lazyload" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="<?php echo $image->resize(480)->url() ?>" width="<?php echo $image->resize(480)->width() ?>" height="<?php echo $image->resize(480)->height() ?>">
<div class="caption" style="display:none">
<h4><?php echo $site->find('projets')->children()->visible()->sortBy('sort', 'asc')->title() ?></h4>
</div>
</a>
<figcaption class="heart">
</figcaption>
</figure>
</article>
<?php endforeach ?>
JS
$(function(){
var element = $('.projects');
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;
});
});
});