Still relevant: filter a page collection by language

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… :confused: I will post my own solution here when I’m done.

Well, this turned out to be a lot easier than it seemed, at least for my use case. :slight_smile: 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:

{% 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 Likes