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.

Themes & Styling

Getting page content element from page collection

Started by binary.koala 3 years ago · 4 replies · 610 views
3 years ago

Hi,

I'm very new to Grav and looking for a way to extract page child element from page.collection array, alike getting images using a loop:

TWIG
{% for p in page.collection %}
    <li><a href={{ p.url }}>{{ p.title }}</a></li>
    {% for image in p.media.images %}
      <li><img src={{ image.url }} /></li>
{% endfor %}

but instead something alike this:

TWIG
{% for p in page.collection %}
   {% for child in p.content %}
      <li>{{ child }}</li>
    {% endfor %}
{% endfor %}

while expecting to get a list of content child elems like <p>..</p> and such.

Looking for Twig ways of doing this i found this that mentions Twig tweak module - would it be an option within Grav and if, how would one add a Twig module to Grav?

Any other solution would be just as welcome too ;)

Cheers

3 years ago

@binary.koala, Do you want to loop through all pages in page.collection and list all children of the current page in the loop?

If so, you could try:

TWIG
{% for p in page.collection %}
   {% set pChildren = p.evaluate(['@self.children']) %}
   {% for child in pChildren %}
      <li>{{ child.title }}</li>
    {% endfor %}
{% endfor %}

If not, please explain what you are trying to achieve.

3 years ago

Hi, thanks for the response.

What I would like to achieve is to be able to extract partial content of child, say first <p></p>.

{{ child.summary }} gets me pretty close but i would still like to be able to pick-out only the first <p></p> HTML element from that output. Should I be using a custom filter?

3 years ago

@binary.koala,

Should I be using a custom filter?

There is a Twig function regex_match you could try.

According the docs:

A helpful wrapper for the PHP preg_match() method, you can perform complex regular expression match on text via this filter:

regex_match('http://www.php.net/index.html', '@^(?:http://)?([^/]+)@i')

JS
Array
(
    [0] => http://www.php.net
    [1] => www.php.net
)
👍 1

Suggested topics

Topic Participants Replies Views Activity
Themes & Styling · by Pedro M, 2 months ago
4 193 2 months ago
Themes & Styling · by Ian, 2 months ago
3 90 2 months ago
Themes & Styling · by Norbert, 2 years ago
11 449 3 months ago
Themes & Styling · by Lukáš Findeis, 3 months ago
0 43 3 months ago
Themes & Styling · by Sebadamus, 4 months ago
5 123 3 months ago