Hello everyone, I’m wondering if there is an opportunity to do LoadMore Function for Structured Field
Im create controller
<?php
return function($site, $pages, $page) {
$testimonials = $page->testimonials()->toStructure();
$count = $testimonials->count();
if(r::ajax() && get('offset') && get('limit')) {
$offset = intval(get('offset'));
$limit = intval(get('limit'));
$testimonials = $testimonials->offset($offset)->limit($limit);
$more = $count > $offset + 1;
} else {
$offset = 0;
$limit = 2;
$more = null;
$testimonials = $testimonials->limit($limit);
}
return [
'offset' => $offset,
'limit' => $limit,
'more' => $more,
'testimonials' => $testimonials,
];
};
Main page template
<?php snippet('header') ?>
<!-- Testimonials -->
<div class="container" align="center">
<div class="row testimonials" data-limit="<?= $limit ?>">
<?php foreach($testimonials as $testimonial): ?>
<?php snippet('testimonial', compact('testimonial')) ?>
<?php endforeach ?>
</div>
<center><a href="#load-more" class="btn btn-outline-secondary mt-3">load more</a></center>
</div>
<!-- End of Testimonials -->
<?php snippet('footer') ?>
Json Template
<?php
$html = '';
foreach($testimonials as $testimonial) {
$html .= snippet('testimonial', compact('testimonial'), true);
}
$data['html'] = $html;
$data['more'] = $more;
echo json_encode($data);
And the JS
var element = $('.testimonials');
var limit = parseInt(element.data('limit'));
var offset = limit;
$('#load-more').on('click', function(e) {
$.get({limit: limit, offset: offset}, function(data) {
if(data.more === false) {
$('#load-more').hide();
}
element.children().last().after(data.html);
offset += limit;
});
});
I can’t see any errors. But when I click on Load More button it redirects me on home page.