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.

Forms & Blueprints

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

twig

Solved by pamtbaau View solution

Started by the rock 3 years ago · 3 replies · 444 views
3 years ago

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 :) 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:

TWIG
{% 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:

TWIG
{% 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!

3 years ago

@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?

last edited 09/19/23 by pamtbaau
3 years ago

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

TWIG
{% 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?

3 years ago Solution

@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
last edited 09/20/23 by pamtbaau

Suggested topics

Topic Participants Replies Views Activity
Forms & Blueprints · by Ton Haarmans, 5 years ago
13 1136 4 months ago
Forms & Blueprints · by Hugo Oliveira, 5 months ago
0 61 5 months ago
Forms & Blueprints · by Flachy Joe, 6 months ago
9 134 6 months ago
Forms & Blueprints · by Augustus, 7 months ago
7 110 7 months ago
Forms & Blueprints · by Julien, 7 months ago
10 129 7 months ago