symfony2 twig 白名单 html 标签 [英] symfony2 twig whitelist html tags

查看:36
本文介绍了symfony2 twig 白名单 html 标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Symfony2 中将一个变量传递给我的 twig 模板,这个变量可能包含 <br/> html 标签,我试图创建一个扩展(函数),但变量仍然得到逃跑了.

I pass a variable to my twig template in Symfony2, this variable may contain <br /> html tags, I have tried to create an extension (function), but the variable still gets escaped.

如何输出允许 <br/> 标签的 twig 变量?是否有一个简单的解决方案只允许某些模板中允许的标签白名单?

How can I output a twig variable that allows the <br /> tag? Is there a simple solution to just allow a whitelist of allowed tags in certain templates?

我搜索过 twig 沙箱,但我不确定这是否是我的解决方案.

I've searched about twig sandboxes, but I'm not sure if that is my solution.

我仍然希望对变量进行转义,但只允许 <br/> 标记.

edit: I still want the variable to be escaped, but to allow exclusively the <br /> tag.

推荐答案

最初我认为应该可以编写自定义转义策略,以便您可以执行以下操作:

Initially I thought it should be possible to write custom escaper strategies so you could do something like this:

{{ var|escape('html-custom') }}

不幸的是,事实并非如此.唯一可用的策略是 html 和 js.它们被硬编码在 Twig_Extension_Core 类文件中定义的 twig_escape_filter() 函数中.

Unfortunately it's not the case. Only available strategies are html and js. They're hard coded in the twig_escape_filter() function defined in a Twig_Extension_Core class file.

看来您唯一的选择是使用新过滤器编写自定义 estension:

It seems that your only option is to write custom estension with a new filter:

{{ var|raw|customescape }}

以下是自定义 twig 扩展的示例以及如何在 Symfony 中注册它:Symfony2 Twig 扩展

Here's an example of custom twig extension and how to register it in Symfony: Symfony2 Twig extension

这篇关于symfony2 twig 白名单 html 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆