I have events page and templates/events.php
for it:
<div class="page__container">
<?php snippet('events/events', [
'type' => 'future',
'eventsList' => $eventsFuture,
'eventsListPagination' => $paginationFuture
]) ?>
<?php snippet('events/events', [
'type' => 'past',
'title' => t('past-events'),
'eventsList' => $eventsPast,
'eventsListPagination' => $paginationPast
]) ?>
</div>
Controller controllers/events.php
:
<?php
return function ($kirby) {
$limit = 5;
$eventsFuture = $kirby->collection('events-future')->paginate($limit);
$eventsPast = $kirby->collection('events-past')->paginate($limit);
return [
'limit' => $limit,
'eventsFuture' => $eventsFuture,
'eventsPast' => $eventsPast,
'paginationFuture' => $eventsFuture->pagination(),
'paginationPast' => $eventsPast->pagination(),
];
};
Events list snippet:
<ul class="events__list _row-md" data-events="<?= $type ?>" data-page="<?= $eventsListPagination->nextPage() ?>">
<?php foreach($eventsList as $event): ?>
<?php snippet('events/event', [ 'event' => $event ]) ?>
<?php endforeach ?>
</ul>
<?php if($eventsListPagination->hasNextPage()): ?>
<button
class="button _more-link _down events__more-link"
type="button"
accesskey="m"
>
<span class="button__text"><?= t('button-show-more') ?> 5</span>
</button>
<?php endif ?>
Controller for JSON — controllers/events-past.json.php
:
<?php
return function ($kirby) {
$limit = 5;
$events = $kirby->collection('events-past')->paginate($limit);
$pagination = $events->pagination();
$more = $pagination->hasNextPage();
return [
'events' => $events,
'pagination' => $pagination,
'more' => $more,
'html' => '',
'json' => [],
];
};
Template for JSON — templates/events-past.json.php
:
<?php
foreach($events as $event) {
$html .= snippet('events/event', ['event' => $event], true);
}
$json['html'] = $html;
$json['more'] = $more;
echo json_encode($json);
And JS for load more button:
containers.forEach(container => {
let page = Number(container.getAttribute('data-page'));
if (!page) {
return;
}
const button = container.nextElementSibling;
const type = container.getAttribute('data-events');
const fetchProjects = async () => {
const url = `${window.location.href.split('#')[0]}-${type}.json/page:${page}`;
try {
const response = await fetch(url);
const { html, more } = await response.json();
button.hidden = !more;
container.insertAdjacentHTML('beforeend', html);
page++;
} catch (error) {
console.log('Fetch error: ', error);
}
};
button.addEventListener('click', fetchProjects);
});
I see first 5 items of events list and load more button. When I click the button I get error:
GET http://localhost:8000/en/events-past.json/page:2 404 (Not Found)
Fetch error: SyntaxError: Unexpected token ‘<’, "<!doctype "… is not valid JSON