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.

Support

Split content by regex and extract H2

theme

Solved by Niko Kaindl View solution

Started by Niko Kaindl 5 years ago · 3 replies · 725 views
5 years ago

Is it possible to extract H2 Headline from {{ page.content }} ? Something like:

TWIG
{% for tabtitle = regex_filter(page.content, "/(?<=<h2>)(.*?)(?=</h2>)/") %}

{{ tabtitle }}

{% endfor %}

However I would not know how to split up page.content, to make that work. Also

And then get the text between the H2 headlines.

TWIG
{% for tabcontent in regex_split(page.content, "/<h2>(.*?)</h2>/") %}

{{ tabcontent }}

{% endfor %}

I did not find any examples of that. Any ideas, how I would be able to do that?

last edited 07/13/21 by Niko Kaindl
5 years ago Solution

I solved it. I had to add preg_match_all (matchall) as custom filter. The other part was possible with regex_replace and split:

TWIG
{% for item in page.content|matchall('~(?<=<h2>)(.*?)(?=<\/h2>)~')[1] %}

{{ item }}

{% endfor %}
TWIG
{% for item in regex_replace(page.content, ['~<h2>(.*?)</h2>~'], ['<hr />'])|split('<hr />')|slice(1) %}

        {{ item }}

{% endfor %}
5 years ago

@NEA, I think your reply would be so much more valuable to other community members if you add the definition of the custom filter you've created.

Suggested topics

Topic Participants Replies Views Activity
Support · by Thomas, 1 week ago
2 53 11 hours ago
Support · by Anna, 3 days ago
2 60 13 hours ago
Support · by Justin Young, 14 hours ago
1 30 14 hours ago
Support · by Duc , 1 week ago
2 65 5 days ago
Support · by Colin Hume, 1 week ago
2 56 5 days ago