Ron Piggott Ron Piggott - 9 months ago 74
Twig Question

Parse Text In Twig View In ZF2

I am designing the opening page of my personal web site. I am trying to use the same service function as the 'blog' section opening which retrieves the latest blog entry.

However I only want up to the 2nd paragraph to display on the opening page of my person web site. For me to re-use the service function I would need to parse after the second


within Twig. In other words I would want something like

<p>blah1 blah1 blah1</p>

<p>blah2 blah2 blah2</p>

to be the result. What syntax is needed in Twig?

Answer Source

You could do something like this...

Let's say that your text content is inside a twig variable named content.

Split your text content on every occurrence of </p>:

  {% set contentArray = content|split('</p>') %}

First paragraph is everything inside first element of array after the first occurrence of <p>

{% set firstParagraphArray = contentArray[0]|split('<p>') %}
{% set firstParagraph = '<p>' ~ firstParagraphArray[1] ~ '</p>' %}

Second paragraph:

{% set secondParagraph = contentArray[1] ~ '</p>' %}


  {% autoescape %}
      {{ (firstParagraph ~ secondParagraph)|raw }}
  {% endautoescape %}

Alternatively, you could make twig extension, that does all this job, and makes twig code a little bit cleaner.