Twig: How to load page data from a type:pages field?

Hello there, I’ve been using Grav CMS for quite a while and am familiar with creating blueprints and using new fields in my twig templates :slight_smile: it’s a lot of fun so far!

what I am struggling with now is a field with the type “pages”, where users can set a page as the “top article”. so far, it has always been the newest article:

{% set newest_article = page.collection({
                'items': '@root.descendants',
                'filter': {
                    'type': 'article',
                },
                'order': {
                    'by': 'date',
                    'dir': 'desc',
                },
                'limit': 1
            }) %}

now I’d like to do something like:

{% if page.header.topArticle %}
            {% set newest_article = page.find(page.header.topArticle) %}
        {% else %}
            {% set newest_article = page.collection({

But I cannot get it to work and been searching for hours… How do I “load” a page from a type:pages field?

Thanks!

@rock, Both snippets in which you set newest_article should be fine, however, one returns a Page and the other a Collection.

But I cannot get it to work

What exactly?

Oh ok thanks for the answer! What I am doing afterwards is the following:

{% for article in newest_article %}
  <a href="{{article.url}}" class="article" title="{{ article.title }}">

it makes sense now, that this is only working if newest_article is a Collection. What would be the approach to make it work in both cases?

@rock,

You’re close. A few hints should do…

  • Variable newest_article from using page.find() is a Page
  • Variable article inside your for loop is a Page
  • page.collection(...).first returns the first Page in a collection
1 Like