1

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.

1 Answer 1

1

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).

2
  • By limit do you mean split? How would I change this to pull five paragraphs for example? Not following how split(0, -1) works. Thanks!
    – univers_
    Sep 4, 2020 at 4:53
  • split is a Twig Filter that takes a mandatory parameter (the delimiter) and an optional one (the limit). The limit limits the size of the array returned by the split filter. Take a look at the split filter documentation (twig.symfony.com/doc/2.x/filters/split.html), I have no idea how to explain it better.
    – nstCactus
    Sep 4, 2020 at 8:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.