Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top