Skip to content
Grav 2.0 is officially stable. Read the announcement →

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

General

Still relevant: filter a page collection by language

Solved by Anna View solution

Started by Anna 6 years ago · 1 replies · 687 views
6 years ago

Hey everyone,

I would like to filter a page collection by language. I have found two relevant forum posts for this, both offering a solution:

  1. Someone with the same problem solved it by translating all pages, then setting the "unwanted" translations to unpublished. That would surely work, however I'm looking at over a hundred pages, so that's not very practical.
  2. The very same question asked by somebody else in April 2018 with a hint to the Page object's translatedLanguages method. The referenced article has since been removed, so I'm not finding this too helpful.

I will check out that translatedLanguages method and probably cobble together something that works, but I am quite surprised that not that many people seem to have a need for this sort of thing. I guess if your translated pages follow mostly the same structure as the default language, it's probably not an issue. In my case however, I have a large and evolving website in German that is getting an international version in English (mostly). This will have much less content, and also differing content, so even the same menu structure doesn't make much sense. Hm.

I really don't understand enough of Grav to know whether it's a big deal adding a language filter to page collections… 😕 I will post my own solution here when I'm done.

6 years ago Solution

Well, this turned out to be a lot easier than it seemed, at least for my use case. 🙂 In the menu loop that iterates over the page collection (that contains all visible pages regardless of language), I simply added another {% if %} tag in the twig:

TWIG
{% set options = { items: {'@root.children':''}, 'order': {'by': 'folder', 'dir': 'asc'}} %}
{% set menu = page.collection(options).visible %}

<ul>
{% for p in menu %}
  {% if p.language == grav.language.getLanguage %}
    // do list output here
  {% endif %}
{% endfor %}

Bam! That's it. Works perfectly for me – maybe it can help somebody else out sometime.

👍 2

Suggested topics

Topic Participants Replies Views Activity
General · by Jerry Hunt, 4 days ago
2 125 19 hours ago
General · by pamtbaau, 1 day ago
1 89 24 hours ago
General · by Andy Miller, 2 days ago
0 73 2 days ago
General · by Marcel, 12 months ago
6 382 5 days ago
General · by Duc , 6 days ago
3 69 6 days ago