我正在使用短条件来区分记录列表中显示的值。
例如,如果我希望强调 ( <em> </em>
) 标识符大于 100 的客户的姓名,请执行以下操作:
{# Displays the identifier of the client #}
{% set strClient = '<em>' ~ client.name ~ '</em>' %}
{{ Client.id > 100 ? strClient|raw : client.name }}
此处 HTML 由浏览器处理,并强调显示客户名称,事实是,例如,如果您想显示您的电话,可以为 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 标记。
有谁知道如何让 Twig 中的 HTML 字符串被解释?
最佳答案
当使用带有 tenary 的原始过滤器时,如果您需要将整个语句包装在括号中以使其工作。
例如{{ (Client.id > 100 ? client.tel : '<em> Not found </em>')|raw }}
关于html - 短 if 内的原始 Twig 变量过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30642416/