如何在Twig中从字符串中移除换行符

13

我有以下代码:

{% set pageDescription = item.description|length > 197 ? item.description|striptags|trim|slice(0, 197) ~ '...' : item.description %}

我将从 item.description 中移除换行符。

例如,我有以下内容:

<meta name="description" content="An easy playing game about the natural numbers. There will randomly appear the natural. You have to choose what the right after number is. It&amp;#8217;s so easy to play this game, isn&amp;#8217;t it?

The..." />

转换为

<meta name="description" content="An easy playing game about the natural numbers. There will randomly appear the natural. You have to choose what the right after number is. It&amp;#8217;s so easy to play this game, isn&amp;#8217;t it? The..." />

我可以帮助您做什么?

谢谢。


1
你尝试过使用 |replace({ "\n": "" }) 吗? - Maerlyn
3
为了保留文本中的换行符,请使用{{ post.content | replace({ '\r\n': '\\r\\n', '\n': '\\n', '\r': '\\r' }) }}作为唯一正确的方法,如果要删除换行符,则可以使用{{ post.content | replace({ '\r\n': '', '\n': '', '\r': '' }) }}。请注意不改变原意,并使翻译通俗易懂。 - caw
2个回答

25

尝试使用|replace过滤器。

|replace({"\n": "", "\r": "", "\t": ""})

例如
{{ item.description|replace({"\n": "", "\r": "", "\t": ""}) }}

由于某些原因,我最终需要使用|replace()过滤器和{% spaceless %}标签。 - sagannotcarl

3
如果你只需要 HTML 标签,可能使用 spaceless 标签{% spaceless %} ... {% endspaceless %} 就足够了。

这不是机器翻译!我必须同时使用 spacelessreplace - Sami
使用Twig 3,可以这样写:{% apply spaceless %} ... {% endapply %} - Sami

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接