Greg
Greg

Reputation: 836

truncate in twig on html content

I would like to truncate a long string, who content html tag.

From my controller php.

content="<div>
<h1>my title</h1>
<p>para 1 ...</p>
</div>";

I would like to truncate this, so i did this in twig :

{{ content|raw|truncate(15) }}

But the html are broken, see bellow :

<div>
<h1>my ti...

I want to keep the end of tag, like this :

<div>
<h1>my titl...</h1>
</div>

Anyone have an idea ?

Upvotes: 1

Views: 5470

Answers (2)

doydoy44
doydoy44

Reputation: 5782

You can solve this with the text-truncate class of bootstrap.

<h1 class="text-truncate">my title</h1>

If you don't want to use bootstrap, you can do it directly in css with the property text-overflow:ellipsis as it is the case in bootstrap.

Here is an example in css.

I hope it will help you.

Upvotes: 1

Matteo
Matteo

Reputation: 39460

You can use the Twig Truncation Extension. As you can read in the doc:

{% set html %}
    <h1>Test heading!</h1>
    <ul>
        <li>Hello world</li>
        <li>Foo bar</li>
        <li>Lorem Ipsum</li>
    </ul>
{% endset html %}
{{ html|truncate_letters(20) }}

will output:

<h1>Test heading!</h1>
<ul>
    <li>Hello wo</li>
</ul>

Hope this help

Upvotes: 2

Related Questions