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

Get page's highest-level ancestor

Started by Muut Archive 10 years ago · 3 replies · 457 views
10 years ago

I'm aware this can be done with a recursive Twig macro if you're after a certain property of the ancestor, eg.:

TWIG
{% macro granddaddy_image(p) %},{% spaceless %}

  {% if p.parent.root %}
    {{ (p.media.images|first).url }}
  {% else %}
    {{ _self.granddaddy_image(p.parent) }}
  {% endif %}

{% endspaceless %},{% endmacro %}

<img src="{{ _self.granddaddy_image(page) }}" alt="img">

Is there a way of quickly retrieving the highest-level ancestor page as an object?

10 years ago

You can quickly reach the root like this:

TWIG
{% set root = pages.root %}

however, that's really a placeholder for the root node of user/pages/, within that are a bunch of top-level pages usually, and to get those you can do:

TWIG
{% set root_pages = pages.root.children %}

However, to get the root page of the current page you are in, you must loop and climb back up the way you are already doing.

10 years ago

I'm not after the root, though - I'm after the node below that (relative to this page).

10 years ago

Then climbing back up, looping until the next parent is root is the way to go.

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1366 9 years ago
Archive · by Muut Archive, 9 years ago
2 940 9 years ago
Archive · by Muut Archive, 9 years ago
2 4069 9 years ago
Archive · by Muut Archive, 9 years ago
1 2960 9 years ago
Archive · by Muut Archive, 9 years ago
3 1125 9 years ago