truncate in twig on html content

自古美人都是妖i 提交于 2021-01-28 08:13:37

问题


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 ?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/52839025/truncate-in-twig-on-html-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!