I have a rich text output section I want to limit to the first paragraph so I can link to a full version on another page. What's the best way to do this?
3 Answers
You can do this entirely with Twig.
First, use the |split
filter to split your HTML into an array of paragraphs, on their closing </p>
tags:
{% set paragraphs = entry.myRichTextField|split('</p>') %}
Then, you can assign the first paragraph to a new variable using the |first
filter. And don’t forget to bring back that missing </p>
.
{% set firstParagraph = paragraphs|first ~ '</p>' %}
Finally, you can output that. Use the |raw
filter so that Twig doesn’t encode the HTML entities.
{{ firstParagraph|raw }}
-
This outputs a strings like this: "<p>This is outputted text</p>" Is there an easy way to get rid of those <p> tags in that string or to make them actually format the text? Commented Jul 2, 2014 at 16:29
-
@AllenPieper Sorry about that, forgot to include the
|raw
filter. Updated my answer. Commented Jul 2, 2014 at 16:32 -
{{ entry.body|split('</p>')|first|raw }}
seems to be working too– 321zenoCommented Feb 9, 2017 at 19:05
In case anyone is wondering how you get the rest of the text – here is an example:
{# Split paragraphs using a limit of 2 #}
{% set paragraphs = block.body|split('</p>', 2) %}
{# Get first paragraph and add the missing closing tag #}
{% set firstParagraph = paragraphs|first ~ '</p>' %}
{{ firstParagraph|raw }}
{# The rest of the text is here, due to the limit in the split filter #}
{{ paragraphs|last|raw }}
Just for reference, if you use a regular Rich Text field for an optional custom Post Excerpt and a Matrix field (with a "text" field in it, among others) for the Post Body, you could check the custom excerpt for content and otherwise output the first paragraph of the text field in the first Matrix block of type textBlock:
{% for entry in craft.entries.section('blog').find() %}
<h2>{{ entry.title }}</h2>
<div class="post-summary">
{% if entry.postExcerpt | length %}
{# Custom Excerpt #}
{{ entry.postExcerpt }}
{% elseif entry.postBody.type('textBlock').first() | length %}
{# Auto Excerpt: in postBody Matrix, find first text block and extract first paragraph #}
{% set first_block = entry.postBody.type('textBlock').first() %}
{% set first_block_text = first_block.text %}
{% set paragraphs = first_block_text|split('</p>') %}
{% set first_paragraph = paragraphs|first ~ '</p>' %}
{{ first_paragraph | raw }}
{% endif %}
</div>
<p><a href="{{ entry.url }}">Read More</a></p>
{% endfor %}