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

Split content by regex and extract H2

theme

Solved by Niko Kaindl View solution

Started by Niko Kaindl 5 years ago · 3 replies · 788 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 BenLaKnet, 6 days ago
1 123 2 days ago
Support · by BenLaKnet, 1 week ago
5 195 2 days ago
Support · by kskt, 3 days ago
0 45 3 days ago
Support · by David Meissner, 3 days ago
0 45 3 days ago
Support · by David Meissner, 4 days ago
3 92 3 days ago