TransWikia.com

Get first X paragraphs, then output the rest

Craft CMS Asked by univers_ on January 31, 2021

The below is code that works to only show the first paragraph, then show the rest. Is it possible to instead, show the first five or six paragraphs, then show the rest?

{# 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 }}

Wordsmith works for this, but I’m unable to see a way to output the rest of the paragraphs.

One Answer

Seems like a huge hack to me but here's how to do it:

{# Split paragraphs using with a limit of 3 #}
{% set paragraphs = text|split('</p>', 3) %}

{# Get an array containing the first 2 paragraphs, and convert it back to a string, adding missing closing tags  #}
{% set firstParagraphs = paragraphs|slice(0, -1)|join('</p>') ~ '</p>' %}

{{ firstParagraphs|raw }}

{# The rest of the text is here, due to the limit in the split filter #}
{{ paragraphs|last|raw }}

To adjust the number of paragraphs in your first group, just change the limit parameter of the join twig filter (this is a bit counter intuitive, see the Twig documentation to understand the logic).

Answered by nstCactus on January 31, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP