Giter Club home page Giter Club logo

grav-plugin-pagination's Introduction

Grav Pagination Plugin

Pagination is a Grav Plugin that allows to divide articles into discrete pages.

Installation

To install this plugin, just download the zip version of this repository and unzip it under /your/site/grav/user/plugins. Then, rename the folder to pagination.

You should now have all the plugin files under

/your/site/grav/user/plugins/pagination

NOTE: This plugin is a modular component for Grav which requires Grav, the Error and Problems plugins, and a theme to be installed in order to operate.

Config Defaults

enabled: true
built_in_css: true
delta: 0

The 'delta' value controls how many pages left and right of the current page are visible. If set to 0 all pages will be shown.

If you need to change any value, then the best process is to copy the pagination.yaml file into your users/config/plugins/ folder (create it if it doesn't exist), and then modify there. This will override the default settings.

Usage for content authors

To use this plugin:

  • the pagination plugin must be installed and enabled
  • the active theme must have pagination support (most Grav themes support pagination; if you’re building your own theme, see the next section for adding pagination support)

On the content side, you should have a blog-like structure, for example:

blog/
    blog.md
    my-cool-blog-post/
        item.md
    another-post/
        item.md

Then in your blog.md, set up the page’s collection using YAML front-matter:

---
title: My Gravtastic Blog
content:
  items: '@self.children'
  order:
    by: header.date
    dir: desc
  pagination: true
  limit: 10
---

# My Gravtastic Blog
## A tale of **awesomazing** adventures

Your /blog page should now list the 10 most recent blog posts, and show pagination links.

Usage for theme developers

Including the default pagination template

If you are developing your own theme and want to support pagination, you need to include the pagination template in the relevant pages. For instance in blog.html.twig:

{# /your/site/grav/user/themes/custom-theme/templates/blog.html.twig #}

{% set collection = page.collection() %}

{# Render the list of blog posts (automatically filtered when using pagination) #}
{% for child in collection %}
   ...
{% endfor %}

{# Render the pagination list #}
{% if config.plugins.pagination.enabled and collection.params.pagination %}
    {% include 'partials/pagination.html.twig' with {'base_url':page.url, 'pagination':collection.params.pagination} %}
{% endif %}

Overriding the pagination HTML

If you want to override the look and feel of the pagination, copy the template file pagination.html.twig into the templates folder of your custom theme:

/your/site/grav/user/themes/custom-theme/templates/partials/pagination.html.twig

You can now edit the override and tweak it to meet your needs.

Twig pagination function

It is now possible to create paginated collections on demand in your twig file. You only need to:

  • activate the pagination plugin
  • pick or create the collection you want
  • paginate it
  • render the paginated collection

Creating a paginated collection

Basic usage

{# some collection #}
{% set collection = page.collection() %}
{# number of items per page #}
{% set limit = 5 %}
{% do paginate( collection, limit ) %}

This creates a paginated collection with limit items per page. As usual, any url parameters - except the page parameter, which is recreated - are passed on to the pagination bar's links.

Extended usage

{% set collection = page.find( '/other/_events' ).children %}
{% set limit = 5 %}
{% set ignore_url_param_array = [ 'event' ] %}
{% do paginate( collection, limit, ignore_url_param_array ) %}

The above example is taken from http://ami-web.nl/events. This code creates a paginated collection with 5 items per page (the event summary list) which is presented together with an active event. The active event appears in only one of the summary pages. Consequently, the url parameter 'event' should be filtered out so it does not show up in the pagination bar's links, preventing inconsistencies with different page parameters. Any non listed url parameters (except the page parameter) are passed through unaffected. The requested page contains logic to pick a sensible default event.

Rendering the paginated collection

The rest is identical to the standard procedure:

{# create list of items #}
{% for item in collection %}
   ...
{% endfor %}

{# include the pagination bar #}
{% if config.plugins.pagination.enabled and collection.params.pagination %}
    {% include 'partials/pagination.html.twig' with {'base_url':page.url, 'pagination':collection.params.pagination} %}
{% endif %}

grav-plugin-pagination's People

Contributors

flaviocopes avatar gigago avatar lufog avatar mahagr avatar rhukster avatar robwent avatar ryanmpierson avatar seebz avatar w00fz avatar whollaus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

grav-plugin-pagination's Issues

grav pagination can't see feature page data

i've created feature modular page and add some of data using grav admin theme tabs my markdown file data is below.

title: Features
media_order: 'pexels-photo-1040157.jpeg,pexels-photo-1509428.jpeg,pexels-photo-2076622.jpeg'
published: true
class: small
features:
-
icon: 'fa fa-music'
header: Music
text: 'Music Description'
url: www.Google.com
description: Image
new_image: pexels-photo-1509428.jpeg
customimage:
user/themes/quark/images/bRpETMJx3yjBGrU.jpg:
name: bRpETMJx3yjBGrU.jpg
type: image/jpeg
size: 133533
path: user/themes/quark/images/bRpETMJx3yjBGrU.jpg
-
icon: 'fa fa-signal'
header: Signal
text: 'Signal Description'
url: www.google.com
description: image
new_image: pexels-photo-2076622.jpeg
customimage:
user/themes/quark/images/EOqkf2DMUmIwY4o.jpg:
name: EOqkf2DMUmIwY4o.jpg
type: image/jpeg
size: 214082
path: user/themes/quark/images/EOqkf2DMUmIwY4o.jpg
-
icon: 'fa fa-video-camera'
header: video
text: 'Video Description'
url: www.google.com
description: image
new_image: pexels-photo-1509428.jpeg
customimage:
user/themes/quark/images/D2my3isrQu46LvJ.jpg:
name: D2my3isrQu46LvJ.jpg
type: image/jpeg
size: 833597
path: user/themes/quark/images/D2my3isrQu46LvJ.jpg
-
icon: 'fa fa-volume-up'
header: Sound
text: 'Sound text'
url: Sound.com
description: 'Sound description'
new_image: pexels-photo-1509428.jpeg
customimage:
user/themes/quark/images/0pA4mzu3DxlPQFJ.jpeg:
name: 0pA4mzu3DxlPQFJ.jpeg
type: image/jpeg
size: 52057
path: user/themes/quark/images/0pA4mzu3DxlPQFJ.jpeg

I need to create pagination.

Finding Page URL

I am using a if statement to target the first story in the loop, naming it 'feature-story'. When I use this pagination plugin, that loop starts over, creating a "feature story' on the second page. Is there a way for me to write a if statement that basically creates the feature story ONLY on the first page? Something like:

{% if loop.first and pagination == page1 %}

Deprecated GravTrait used

The following warning is flooding the Grav debugger:

Deprecated GravTrait used in [...]/user/plugins/pagination/classes/paginationhelper.php

feature request: ignore url params

By default, the pagination plugin copies any and all url parameters when creating the pagination links. Sometimes, this behaviour is undesirable, specifically when a copied parameter conflicts logically with the presented page's contents. Take for example, a paginated list of unique items with a 'selected item' view, which should at all times match the selection in the visible slice of the list. The selected item may initially be indicated by an url parameter or it may be some default, like the first item on a given list page. However, it can never be present on more than one page. In this case, passing on the parameter via pagination links makes no sense and requires elaborate workarounds to prevent things from breaking. The cleanest solution is to optionally disable the reuse of url parameters by pagination. The following is a rudimentary site-wide implementation.

Note: this does not alter the pagination 'page' parameter itself which, as before, is appended to the base url after pagination.

blueprints

    ignore_url_params:
      type: toggle
      label: Ignore url params
      highlight: 1
      default: 0
      help: Enable this when pagination should ignore url params
      options:
        1: Enabled
        0: Disabled
      validate:
        type: bool

pagination.yaml

ignore_url_params: true

paginationhelper.php

    $url_params = ($config->get('plugins.pagination.ignore_url_params'))?
        ([]):(explode('/', ltrim($uri->params(), '/')));

Get pagination object for any filtered collection

For an article index page that lists blog posts, I was using:

{% for article of page.collection %}
  {# Show link to article #}
{% endfor %}

{% include 'partials/pagination.html.twig' with {
  pagination: page.collection.params.pagination
} %}

But I needed to filter the collection by type because that page contains folders that are not articles. So I switched to:

{% set articles = page.collection.ofType('article') %}
{% for article of articles %}
  {# Show link to article #}
{% endfor %}

{% include 'partials/pagination.html.twig' with {
  pagination: articles.params.pagination
} %}

This work for the links, but not for the pagination which still sees the page count from page.collection().

Shouldn’t .params.pagination represent a pagination object for the collection it’s called from, rather than for the current page?

pagination option not respected when added to a collection in twig

I am having an issue with using pagination as shown in Advanced Collections:

{% set options = { items: '@self.descendants', 'filter': {'type': 'blogpost'}, 'order': {'by': 'date', 'dir': 'desc'}, 'limit': 3, 'pagination': true } %}
{% set collection = page.collection(options) %}

In this case the limit is considered, but there is no pagination shown at all unless I set header.content.pagination to true in the page itself.

I am not sure if this is an issue with the Grav documentation, the pagination plugin or my understanding of how to use it.

"pagination" variable in "pagination.html.twig" doesn't containt the right data.

On a twig template i use the 'Collection Object Methods' to difine a collection like it states in the GRAV documentation:

{% set collection = page.collection({
         'items': '@self.children', 
         'pagination': true, 
         'order': {'by': 'title'}, 
         'limit': 1}) 
%}

I pass this data to the plugin 'pagination.html.twig' template.

{% if config.plugins.pagination.enabled and collection.params.pagination %}
    {% include 'partials/pagination.html.twig' with {'base_url':page.url, 'pagination':collection.params.pagination} %}
{% endif %}

Here i have my issue:

  • "collection.params.pagination" will always return 1 (as 1 is the same as true).

In the plugin template '' the first condition will therefore always return false.

{% set pagination = pagination|default(page.collection.params.pagination) %}
{% if pagination|length > 1 %} ... {% endif %}

Looking inside the plugin template its unclear to me what correct data is expected.
And how to pass this through?

Using pagination breaks isFirst/isLast and siblings calculations

Hi,

Using pagination breaks theme usage of all of the following functions:

  • Collection::isFirst($path)
  • Collection::isLast($path)
  • Collection::prevSibling($path)
  • Collection::nextSibling($path)

Noticed this because it breaks sibling links in themes:

{% set blog_collection = page.find(header_var('blog_url')|defined(theme_var('blog-page'))).collection() %}
{% if not blog_collection.isLast(page.path) %}
  <a class="btn" href="{{ blog_collection.prevSibling(page.path).url }}"><i class="fa fa-angle-left"></i> {{ 'THEME_QUARK.BLOG.ITEM.PREV_POST'|t }}</a>
{% endif %}

Obviously, this happens because the collection on which the functions operate is the paginated version, instead of the source collection.

I'll be poking around with the intent of PRing a solution (either here or in Grav core I guess), hints are appreciated.

Query parameters cleared by pagination

I am using query parameters www.website.com/page:1?param=true for additional filtering. But the current pagination template removes those queries. It would be nice to integrate this into the plugin.

This is my solution:

{% set pagination = pagination|default(page.collection.params.pagination) %}
{% set base_url = base_url|default(page.url) %}

{% if pagination|length > 1 %}

<ul class="pagination">
    {% if pagination.hasPrev %}
        {% set url =  (base_url ~ pagination.params ~ pagination.prevUrl ~ '?' ~ uri.query())|replace({'//':'/'}) %}
        <li><a rel="prev" href="{{ url }}">&laquo;</a></li>
    {% else %}
        <li><span>&laquo;</span></li>
    {% endif %}

    {% for paginate in pagination %}

        {% if paginate.isCurrent %}
            <li><span class="active">{{ paginate.number }}</span></li>
        {% elseif paginate.isInDelta %}
            {% set url = (base_url ~ pagination.params ~ paginate.url ~ '?' ~ uri.query())|replace({'//':'/'}) %}
            <li><a href="{{ url }}">{{ paginate.number }}</a></li>
        {% elseif paginate.isDeltaBorder %}
            <li class="gap"><span>&hellip;</span></li>
        {% endif %}

    {% endfor %}
    {% if pagination.hasNext %}
        {% set url = (base_url ~ pagination.params ~ pagination.nextUrl ~ '?' ~ uri.query())|replace({'//':'/'}) %}
        <li><a rel="next" href="{{ url }}">&raquo;</a></li>
    {% else %}
        <li><span>&raquo;</span></li>
    {% endif %}
</ul>

{% endif %}

Maybe it would make sense to add a variable to enable this new feature to not break older themes. Feel free to use that code!

Since update to v1.4.5 today, pagination broken, shows https://page:2/

I updated the pagination plugin today, to version 1.4.5. To be sure, I also cleared the Grav site’s cache using Admin UI, and reindexed TNT search. I used the Admin UI to update.

I’m running Grav v1.7.44 - Admin v1.10.44.

Now, when clicking the page 2 link on my blog, it tries to access https://page:2/instead of my site.

Help! What can I do to fix this, or maybe revert to the version before?

feature request: twig pagination

I do this with the following code in pagination.php. Hand-kludged from the existing code base, please improve whenever deemed necessary :-) At present, I call this from a twig simplefunc extension, worgs great! Maybe someone has a better proposal for integrating this functionality into grav.

use Grav\Common\Uri;

  /**
     * 'runtime' pagination
     *
     * @param collection $collection
     * @param $limit
     */
    public function paginateCollection(Collection $collection, $limit)
    {
        $collection->setParams(['pagination' => 'true']);
        $collection->setParams(['limit' => $limit]);

        if ($collection->count() > $limit) {
            require_once __DIR__ . '/classes/paginationhelper.php';
            $this->pagination = new PaginationHelper($collection);
            $collection->setParams(['pagination' => $this->pagination]);

            $uri = $this->grav['uri'];
            $start = ($uri->currentPage() - 1) * $limit;

            if ($limit && $collection->count() > $limit) {
                $collection->slice($start, $limit);
            }
        }
    }

Show only a subset of pages in pagination ul.

I am having nearly 60 posts, and the pagination ul at the bottom shows 9 pages.

While this doesn't sound like a lot, but when I viewed the blog on my iPhone, the pagination ul is wider than the screen width and I had to scroll horizontally to see all of it. This also renders our blog non-responsive.

Is it possible to make it "smarter" so that when there are many pages, only show a subset of the page numbers in the pagination ul, so that the ul always fits inside a mobile device?

Pagination does not disappear if no pagination is required.

I found multiple issues with the current pagination plugin. I have some solutions, but you must decide which one will fit best.

My goals:

  • Show a pagination menu if there are items to paginate
  • Hide this menu if there are not enough posts (post count is smaller than pagination limit)

Currently the twig template checks, if the pagination length is greater than 1:

Issue A

The Item index is wrong (one too high). If you have 10 Items, limit set to 5, you'd expect to have 2 paginations. The length will output 3!

for ($x=1; $x <= $this->page_count; $x++) {
if ($x === 1) {
$this->items[$x] = new PaginationPage($x, '');
} else {
$this->items[$x] = new PaginationPage($x, '/page' . $config->get('system.param_sep') . $x);
}
}
}

Fix

We need to place the items to x-1, because the counting starts at 1, not 0.

for ($x=1; $x <= $this->page_count; $x++) {
    if ($x === 1) {
        $this->items[$x-1] = new PaginationPage($x, '');
    } else {
        $this->items[$x-1] = new PaginationPage($x, '/page' . $config->get('system.param_sep') . $x);
    }
}

Edit: This fix break the hasPrev() functions. This can be solved somehow for sure, just noting it here, so you do not forget to change that as well!

Issue B

Now that we have fixed the length, we would expect the pagination menu to disappear, if the limit is not reached. But that does not happen, because now pagination|length will return 4. Why does it happen? Thatswhy:

public function paginateCollection($collection, $limit, $ignore_param_array = [])
{
$collection->setParams(['pagination' => 'true']);
$collection->setParams(['limit' => $limit]);
$collection->setParams(['ignore_params' => $ignore_param_array]);
if ($collection->count() > $limit) {
$this->pagination = new PaginationHelper($collection);
$collection->setParams(['pagination' => $this->pagination]);

pagination is set to true, which is string of length 4.

Fix

We can fix that, by checking the type inside the twig template:

{% if (pagination|gettype == 'object') and pagination|length > 1 %}

However I am not sure, if that is the best way to do. We could also use an empty element, but that caused the whole template to not render at all. But this is an issue you should be able to fix, as I am new to all the code, and you could think of a better solution and you know if they string true is required or not.

Hope that explanation is detailed enough. :-)

Pagination of filtered collection

I can not found any solution for my problem. It looks like pagination issue.
If i use pagination and my collection is filtered like {% set collection = page.collection().ofType('note') %}
i have a wrong pagination which includes an empty page.
For exampe: I have page with limit:3 and 8 children, my page.collection includes 8 items and page should dispalys 3 subpages. After filtering i get only 4 items in my collection and i expect that i will get 2 subpages with 3 and 1 items. But they are still 3, and there are empty subpages.

Can't get Pagination to do page count for current language only

Hi, i have a problem with the pagination plugin I can't get fixed. I changed my blog page twig template to only display posts from the current language, but the pagination still counts all available posts (en fallback) which results in /blog/page:1 showing 1 post, /blog/page:2 showing 0 and /blog/page:3 showing 1 in german, while the english website shows 4 on page:1, 5 on page:2 and 4 on page:3.

I couldn't find a way to tell the pagination to ignore pages that are not available in the current lang (or to set it in the blog pages "blog list -> max item count" setting).

Is this not yet supported by pagination? Or is there something I've missed?

pagination object not global in template

I’m using Grav v1.0.10 and installed the pagination plugin with bin/gpm install pagination.

I’m making pages and templates from scratch. My page has subpages and this YAML front matter:

title: News
content:
    items:
        '@self.children'
    order:
        by: date
        dir: desc
    limit: 5
    pagination: true
pagination: true

(I tried adding the pagination key at two different levels, because I found it at those 2 places depending on the documentation or examples I could find.)

In the template, the pagination object does not exist. After dump()ing things for ages in the debug console, I was able to find that page.collection.params.pagination gives me access to this object.

So when I use:

{% include 'partials/pagination.html.twig' %}

(using the plugin’s template), it doesn’t work because the default template tries to use the global pagination object. But this works alright:

{% include 'partials/pagination.html.twig' with {
    pagination: page.collection.params.pagination
} %}

Also adding /page:2 to the URL works well (it filters the page.collection()). So it’s not a problem of the plugin not working. Just pagination not being global (as the template expects).

Is that expected behavior? If it is expected behavior, could this be documented in the README for this project?

As a side note, it might be useful to add some information about including the partials/pagination.html.twig template if users want to actually have pagination visible in the page. And fixing the broken link in the README (goes to templates/pagination.html.twig, missing the partials/ part).

Lists of collections on pages with the page parameter are not displayed

If I go through the collection, specifically from the page header (item) I take the field author (Admin) and based on it I look in the folder /author page with the corresponding title (Admin) to assign a link (/author/admin), then it works directly in the page with post (/blog/item23) also in the listing on the parent page (/blog), but no longer on pages with the parameter page (/blog/page:2 etc.). However, if I open the post page (/blog/item2), the link is active.

The only thing that occurs to me is that paging affects the transmission of information about the page.

For example:

  1. Correct output (a page /blog/itemN or list of pages on the page /blog):

Title
Author: Admin | Date: 09/02/2021 | Views: 23
Summary or content...

  1. Incorrect output (list of pages on the page /blog/page:N):

Title
Author: | Date: 09/02/2021 | Views: 23
Summary or content...

Get collection|length of paginated collection

I would like to get the length of the collection in a twig template.
If I have a collection of 11 pages:

and I 1) disable pagination or set the limit to 0, I can use this to get the length of a collection:

{% if collection | length > 10 %}
more than your collection of 10 pages.
{% endif %}

However, 2) with pagination enabled and a limit set to 10, this won't work, since the length of the collection is the current paginated collection.

So my question would be: can I (a) calculate the total number of pages somehow, (b) is the number stored in some variable which I have not found yet, or (c) should I implement a workaround (do pagination in twig), like in #13 ?

Feature request: Ability to localize page's param in URL

It is great if the plugin gives an option to change "page" param in URL to something else, like for localization.

For example, I would like to have

myblog.com/bai-viet/trang:10

instead of

myblog.com/bai-viet/page:10

"trang" means "page" in my language.

I looked into the code and I was able to change "page" to a different word, but the page's result was only from page 1 and the pagination only activated page 1, I couldn't browse pages 2+.

use of pagination plugin leaves url:page:whatever opened

Let's say there are 3 pages on a blog page.
url/page:1
url/page:2
url/page:3
If I ask the url/page:4 or url/page:whatever, I should get a 404 error, but I get a blank page.

In my case, therefore I have page referenced by search engines that do not have any content.
Can someone replicate that or is it linked to other parameter like multisite structure of my site?

Thanks in advance for help.

Bad url for 1st page

<div class="post-nav archive-nav pagination">
            <a rel="prev" href="">«</a>
                            <a href="">1</a>
                                <a href="#" class="current">2</a>
                                <a href="/page:3">3</a>
                                <a href="/page:4">4</a>
                        <a rel="next" href="/page:3">»</a>
    </div>

Change ":" to "-" or "/" in pagination url

**Can you make an update to remove ":" from pagination, url to "-" or "/". for example "domain.com/blog/page:2" to "domain.com/blog/page-2" or "domain.com/blog/page/2" or "domain.com/blog/page2"
#53
Screenshot (8)

no base_url

Hello,

clicking on any pagination link, returns https://page:2/

I tried to call {{ base_url }} in user/plugins/pagination/templates/partials/pagination.html.twig

but it's empty. I expect it to be https://{{ domain}}/page:2/

thanks in advance

Builtin css only works when header.pagination is set to true

I want to use the builtin css of the pagination plugin. However it looks like a header variable must be set for that:

if ($page && ($page->value('header.content.pagination') || $page->value('header.pagination'))) {

Since I am using pagination in twig templates (via {% do paginate( collection, limit ) %}), I want to enable the css either in general or at least from the twig template. The current solution seems a bit odd to me, but I might be wrong.

CSS missing with {% do paginate() %}

When doing pagination using the Twig function paginate(), the plugin's CSS is not being added as an asset.

This is probably, because onPageInitialized() checks if the page header has header.content.pagination set - which the page doesn't since I am doing it in the twig template.

Limit word number

Hello everyone.

How can I limit the number of words in pagination?

For example, I've 5 articles of 1500 words.
I want to show the title and the first 100 words.

Plugin ignore twig syntax 'pagination':true

The plugin checks for pagination variable directly and ignores the twig syntax:
if ($page && ($page->value('header.content.pagination') || $page->value('header.pagination'))) {

So if you have something like that in a twig template:
{% set options = { items: {'@page.children': '/blog'}, 'limit':5, 'pagination':true, 'order': {'by': 'date', 'dir': 'desc'} } %}
it will ignore the option 'pagination':true and plugin won't work!
If someone could suggest a solution it would be great.

Forbidden: You don't have permission to access /page:2 on this server.

Tried in Wampserver on Windows 10.
I also downloaded the blog-site skeleton to check whether I screwed something up but the problem still occurs.
I'm pretty sure that I just have to adjust the permissions on a file, but I have no idea which file.
I already tried to chown -R 776 on /user/pages and /user/plugins/pagination but that didn't work.

Error 404 due to removal of protocol slash

In pagination.html.twig it reads:

{% set url =  (base_url ~ pagination.params ~ pagination.prevUrl)|replace({'//':'/'}) %}
…
{% set url = (base_url ~ pagination.params ~ paginate.url)|replace({'//':'/'}) %}
…
{% set url = (base_url ~ pagination.params ~ pagination.nextUrl)|replace({'//':'/'}) %}

These lines cause 404 errors because they also remove a protocol slash (“https:/” instead of “https://”). If changed to the following it works like a charm:

{% set url =  (base_url ~ pagination.params ~ pagination.prevUrl|replace({'//':'/'})) %}
…
{% set url = (base_url ~ pagination.params ~ paginate.url|replace({'//':'/'})) %}
…
{% set url = (base_url ~ pagination.params ~ pagination.nextUrl|replace({'//':'/'}))

Cannot tell if these changes trigger side effects, have not observed so far.

Where does $uri->currentPage() come from?

The plugin uses $uri->currentPage() in multiple lines. For example:

$start = ($uri->currentPage() - 1) * $limit;

It uses a grav API:
https://learn.getgrav.org/16/api#class-grav-common-uri

I am wondering: How does it work? Does the Grav API read the URI and searches for page:<number>? To me this sounds strange, as the pagination should only be provided by the plugin, not by grav itself. I would have expected, that this is a plugin function, not a common API function.

Could you please clarify?

Pagination doesn't work in an embeded page

Running Grav (v1.6.16) and Pagination v1.4.2

Problem

  • When embeding a page in a page (not necessarily with a modular page), pagination does not work correctly : defining a pagination: and limit: option triggers the automatic call of the plugin but the pagination fails in both the parent page (in the "module") and in the sub-page's (when reaching its route).
  • If not using the limit: option, pagination fails in the parent page (the "module" doesn't have the pagination at the bottom) but works when reaching the sub-page.
  • When using the template method (do paginate) to automatically create a collection and define a limit, things work correctly in both the parent page and the sub-page (but we can't define the limit in the blueprint/frontmatter anymore or the first variant of the problem comes back).

Configuration

Page

05.critiques
    01.presse

is a blog. It is intended to display as an embebed module accessible at /critiques
It has 8 items for now.

Frontmatter

(of 01.presse : )

content:
    items: '@self.children'
    pagination: true
    limit: 6
    order:
        by: date
        dir: desc

Blog's template

I've integrated the possibility to detect if a collection is defined, and if not, to define one if the page has children. In the first case, the automatic use of the pagination plugin is triggered, and in the second case the {% do paginate() %} is used.

Also, if a collection is already defined but no limit: option is defined, it is supposed to switch to the manual creation of the pagination.

{# *** Collection preprocessing *** #}
{% if page.collection.count > 0 %}
	{% set collection = page.collection() %}
	{% set limit = page.header.content.limit ?? 6 %}{# Have to use null-coalescing instead of classic ternary, or the plugin bugs ! #}
{% else %}
	{% set limit = '6' %}
	{% set collection_options = { items: {'@page.children': page.url}, 'limit': limit, 'order': {'by': 'date', 'dir': 'desc'}, 'pagination': true } %}
	{% set collection = page.collection(collection_options) %}
{% endif %}
{# *** /Collection preprocessing *** #}

{# *** Manual pagination *** #}
{% if config.plugins.pagination.enabled and collection.params.pagination and not page.header.content.limit %}
	{% do paginate(collection, limit) %}
{% endif %}
{# *** /Manual pagination *** #}

{% for item in collection %}
    ... Display of the items...
{% endfor %}

<div class="footer">
	{% if config.plugins.pagination.enabled and collection.params.pagination %}
		{% include "#{DNA_conf.partials}/pagination.html.twig" with {'base_url':page.url, 'pagination':collection.params.pagination} %}
	{% endif %}
	{% if config.plugins.taxonomylist.enabled %}
		{# include "#{DNA_conf.partials}/taxonomy_list.html.twig" with {'base_url':page.url, 'taxonomy':'tag', 'children_only':false} #}
		{% include "#{DNA_conf.partials}/taxonomy_list.html.twig" with {'base_url':"/critiques", 'taxonomy':'tag', 'children_only':false} %}
	{% endif %}
</div>

Tests performed

The tests I have performed are so numerous that I can't summarize them here.
It is difficult for me to express how things are broken.
As you can see, my template is pretty clean, excepted the IF / ELSE at the begining for automating some sort of detection.

But based on that config, here what I can say :

  1. If I set a paginate / limit in the frontmatter, the collection is detected, the limit variable is created but isn't used because the do paginate won't be triggered. The items are limited on the page, but no pagination appears (no arrow, no numbers).
  2. If use a paginate option but no limit, the collection is detected, a default limit variable is set, and the do paginate is executed. Pagination works fine.
  3. If don't set any pagination nor limit in the frontmatter, the automatic collection creation is realized, and the do paginate is executed too. No pagination shows, and all the items are displayed.

So, as you can see, the problem is we can't define a limit for the pagination in the frontmatter.
And that's a big problem, because it completly breaks the possibility to create a website for a customer, and to give him the possibility to define its own settings with an option in the blueprint.

Intuition

The PHP of the plugin may be processing the presence of a frontmatter option differently than when relying on the template do paginate injection.

That difference could explain the difference of displaying, and the bug.

Facts

collection.params.pagination returns true when using a frontmatter limit: (because the frontmatter's collection isn't defined in the parent page !), instead of returning the whole pagination informations usually used for defining the arrows, the number of pages, etc. So the footer's call of the pagination fails and nothing is displayed.

This means that something is broken in the way the plugin automatically build pagination with the frontmatter. It just means that it doesn't work when embeding a page supposed to have a pagination, in an other page.

filter a collection by 'visible' is not respecting proper count of items on paginated page

{% set posts = page.collection().visible %}

The above declaration of a collection, with the below parameters for display

@self.children
Max Count: 10

with the following display code:

{% for child in posts %}
--- code to display posts ---
{% endfor %}

...should yield 10 posts per page of results, with only visible posts displayed.

However, if the page of results would have had one of the not 'visible' (filtered) items on it, then the results page will only display nine posts, so the count for the posts collection is returning 10 posts per page and just excluding the filtered invisible posts AFTER THE FACT which is throwing off the count.

Shouldn't the filter take only the visible items of the collection and then count them out by tens so that only the visible items are counted?

To test, my reasoning I changed the filter from 'visible' to 'published', like so:

{% set posts = page.collection().published %}

...and changed the not 'visible' pages to not 'published'. After doing so the count is rendered properly with all filtered (unpublished) posts removed prior to the collection count so that ten items display per page. But, of course, the urls for those posts throw a 404 because they are unpublished, so that is not an acceptable workaround.

Any ideas? Let me know if I need to provide more data.

Thanks!

wrong pagination

Hi
pagination error
my header

---
title: Home
body_classes: 'title-center title-h1h2'
content:
    items:
        - '@self.children'
    limit: 16
    order:
        by: date
        dir: desc
    pagination: true
    url_taxonomy_filters: true
---

I use

{% set articlespubl = taxonomy.findTaxonomy({'tag':'publ'}) %}
                {% for post in articlespubl.order('date','desc') %}
                      {% include 'partials/blog-list-item-post.html.twig' with {blog: page, page: child} %}
                {% endfor %}

and recive 11 post in page, and 1-2 pagination with two identical page (1,2)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.