2

What I'm looking for is something that limits the output without breaking tags. Let's say that I have some content for example coming from FCK / MCE:

<p>lorem ipsum lorem ipsum lorem ipsum lorem ipsum  </p>

<p>lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem </p>

<p>lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem </p>

Now for example if I did something like {{ output|raw[:10] ~ '...' }}I would get:

<p>lorem i...

But instead I would like to get:

<p>lorem i...</p>

Any ideas how to accomplish this?

Taruo Gene
  • 1,023
  • 1
  • 9
  • 16

2 Answers2

2

You should try available extension of twig to truncate text in Twig & Symfony2.

Your text is in html so first get plain text using "striptags" filter then apply "truncate" filter of twig.

<p>{{ output|striptags|truncate(50, true) }}</p>

but first you must enable Twig-Text-Extension as following

$twig->addExtension(new Twig_Extensions_Extension_Text());

or in symfony2

// app/config/config.yml
services:
    twig.extension.text:
        class: Twig_Extensions_Extension_Text
        tags:
            - { name: twig.extension }

Following is available options for truncate filter

1 - only truncate

<p>{{ output|striptags|truncate(50) }}</p>

2 - Set second parameter if you want to preserve whole words.

<p>{{ output|striptags|truncate(50, true) }}</p>

3 - Set third parameter if you want use your own separator instead of "..."

<p>{{ output|striptags|truncate(50, true, ".........") }}</p>

for more detail about twig text extension visit http://twig.sensiolabs.org/doc/extensions/text.html

Rajesh Meniya
  • 753
  • 1
  • 7
  • 17
0

If you are sure that it starts with <p> and ends with </p> use this:

{{ output|raw[:10] ~ '...' }}</p>

If you want to find and replace something in your output you can

<p>{{ (output|replace({'<p>': '', '</p>': ''}))|raw[:10] ~ '...' }}</p>
Javad
  • 4,339
  • 3
  • 21
  • 36
  • In the first post I mentioned that the output might come from MCE / FCK so I basically don't know if it's gonna be

    or

    or even tag. So that's not any kind of solution.

    – Taruo Gene Mar 10 '14 at 16:55
  • Oh I see, so in this case you need something like parser to parse whatever comes from MCE/FCK and convert to content you want. You can use `matches` in tiwg to build it with expression [http://twig.sensiolabs.org/doc/templates.html#expressions](Expression in Symfony) – Javad Mar 10 '14 at 17:03
  • Do not forget autoescape for security reasons: http://twig.sensiolabs.org/doc/tags/autoescape.html – Spomky-Labs Mar 10 '14 at 20:34
  • If he auto-escapes, he will display tags instead of intepreting them. As soon as he is using `|raw`, I guess the goal is to display the content as it is (and security had been made at controller side, using [html purifier](http://htmlpurifier.org/) or such). – Alain Tiemblo Mar 11 '14 at 07:31