短 if 内的原始树枝变量过滤器

Raw twig variable filter within a short if

我正在使用短条件来区分记录列表中显示的值。

例如,如果我想要强调 (<em> </em>) 标识符大于 100 的客户的姓名,请执行以下操作:

{# Displays the identifier of the client #}
{% set strClient = '<em>' ~ client.name ~ '</em>' %}
{{ Client.id > 100 ? strClient|raw : client.name }}

此处 HTML 由浏览器处理 并显示客户名称 强调,事实是,如果例如你想显示你的 phone,它可以是 null 也可以不是,如果不是则显示一条强调的消息;我执行以下操作:

{# Displays the customer phone or message if there #}
{{ Client.id > 100 ? client.tel : '<em> Not found </em>' }}

后一种情况HTML标签没有被浏览器处理而显示为纯文本,我也试过以下:

{# Displays the customer phone or message if there #}
{{ Client.id > 100 ? client.tel : '<em> Not found </em>'|raw }}

还有这个:

{# Displays the customer phone or message if there #}
{% set strClient = '<em> Not found </em>' %}
{{ Client.id > 100 ? client.tel : strClient|raw }}

同样的结果,即 when 是一个字符串,这个存储在变量中或者不获取 HTML 标签,总是显示为好像是处理过的纯文本.

有谁知道如何解释树枝中的 HTML 字符串?

当使用带三元的原始过滤器时,如果您需要将整个语句括在括号中以使其工作。

例如{{ (Client.id > 100 ? client.tel : '<em> Not found </em>')|raw }}

在我对你的例子的测试中,none 次尝试成功了,包括你的第一个例子:

{# Displays the identifier of the client #}
{% set strClient = '<em>' ~ client.name ~ '</em>' %}
{{ Client.id > 100 ? strClient|raw : client.name }}

但是,如果您用 {% autoescape false %}{% endautoescape %} 包装您的示例,这应该可以解决问题。如果像这样包装,您的所有示例都应按预期显示:

{% autoescape false %}
{# Displays the customer phone or message if there #}
{{ Client.id > 100 ? client.tel : '<em> Not found </em>' }}
{% endautoescape %}

如果使用自动转义,则不需要 |raw