Skip to main content

Load More

Demo

Installation

Import the function into the JavaScript file of your project

import { LoadMore } from "@overdog/fn"

Create and initialize an instance

new LoadMore("#pages-listing", {
   // options goes here
}).init()

Twig template Code

{# --- TO EDIT entriesPerPage - set your base limit per page #}
{% set entriesPerPage = 2 %}
{# --- LOGIC #}
{# get query param and replace any other characters than numbers #}
{% set urlPageNumber = craft.app.request.getQueryParam('page') %}
{% set formatedPageNumber = urlPageNumber ? urlPageNumber|replace('/[^0-9+]/', '') : 1 %}
{# if pageNumber is not empty after regex replace and bigger than zero, calculate * entriesPerPage, default to entriesPerPage if not #}
{% set queryLimit = (formatedPageNumber and formatedPageNumber > 0) ? entriesPerPage * formatedPageNumber : entriesPerPage %}


{# --- QUERY - only limit is important if you use in other context #}
{% set entriesQuery = craft.entries()
   .section('structureFood')
   .limit(queryLimit)
   .all()
%}

{# --- USE ONLY IF YOU WANT TO HIDE THE LOAD MORE BUTTON ON LAST PAGE #}
{% set totalEntriesCount = craft.entries().section('structureFood').count()%}

{# --- CREATE CHUNKS - to split entries intro paginated DIVs #}
{% set queryChunks = entriesQuery|batch(entriesPerPage) %} 

{# --- LOOP #}
<div id="pages-listing">
   {% for i in range(1, urlPageNumber) %}

      {% set queryChunksPageKey = (i - 1) %}{# the minus 1 is to match the zero from array and 1 from page length #}

      {% if queryChunksPageKey in queryChunks|keys %}
         <div data-fn-load-more-page="{{ i }}" class="mb-half">
            <h3 class="font-bold text-blue-dark mb-quarter">Page-{{ i }}</h3>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-third">
               {% for item in queryChunks[queryChunksPageKey] %}
                  <div class="bg-white p-2 border border-gray-300">
                     <h2 class="text-[1.4em] text-blue my-6 mx-4 font-bold">{{ item.title }}</h2>
                  </div>
               {% endfor %}
            </div>
         </div>
      {% endif %}

   {% endfor %}
</div>

{# --- LOAD MORE BUTTON #}
{% if entriesQuery|length != totalEntriesCount %}
   <button id="load-more-button" class="bg-slate-700 items-center text-white h-[48px] px-8">Load More</button>
{% endif %}

Options