symfony2 twig 白名单 html 标签
我在 Symfony2 中将一个变量传递给我的 twig 模板,该变量可能包含
html 标签,我尝试创建一个扩展(函数),但该变量仍然被转义。
gt;
如何输出允许
标记的树枝变量?是否有一个简单的解决方案仅允许某些模板中允许的标签白名单?
我搜索过树枝沙箱,但我不确定这是否是我的解决方案。
编辑:我仍然希望对变量进行转义,但只允许
标记。
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.
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?
I've searched about twig sandboxes, but I'm not sure if that is my solution.
edit: I still want the variable to be escaped, but to allow exclusively the <br />
tag.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
实际上,您可以通过以下方式使用本机 PHP 函数 strip_tags:
您可以使用以下代码允许多个标签:
Actually, you can use native PHP function strip_tags by following:
you can allow multiple tags with following code:
你可以这样做:
比如,
不会逃跑
,
不会逃跑
等等。
You can do like that :
For instance,
won't escape
and
won't escape
etc.
最初我认为应该可以编写自定义逃生策略,这样你就可以做这样的事情:
不幸的是事实并非如此。唯一可用的策略是 html 和 js。它们被硬编码在
Twig_Extension_Core
类文件中定义的twig_escape_filter()
函数中。看来你唯一的选择是使用新的过滤器编写自定义扩展:
这是自定义树枝扩展的示例以及如何在 Symfony 中注册它: Symfony2 Twig 扩展
Initially I thought it should be possible to write custom escaper strategies so you could do something like this:
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 aTwig_Extension_Core
class file.It seems that your only option is to write custom estension with a new filter:
Here's an example of custom twig extension and how to register it in Symfony: Symfony2 Twig extension
工作正常,但我不知道如何使用这个树枝过滤器将数组传递给 strip_tags php 函数。
两者
都会
在模板渲染期间抛出“数组到字符串转换”异常。
另请注意,strip_tags php 函数不会像“onclick”那样转义 html 属性。
works fine, but I don't know how to pass an array to the strip_tags php function with this twig filter.
both
and
throw an "Array to string conversion" exception during the rendering of a template.
Be also carefull that strip_tags php function doesn't escape html attribute like "onclick".
和/或
nl2br 参考
and/or
nl2br reference