自版本 1.9.0 起,Twig为 escape
过滤器提供 html_attr
策略(参见 documentation )。
html
策略使用 htmlspecialchars PHP 函数(通过快速查看源代码可以确认这一点)。 html_attr
策略使用了一系列自定义替换,这些替换似乎最终具有相同的效果。
这两种策略有区别吗?
最佳答案
source说:
/*
* While HTML supports far more named entities, the lowest common denominator
* has become HTML5's XML Serialisation which is restricted to the those named
* entities that XML supports. Using HTML entities would result in this error:
* XML Parsing Error: undefined entity
*/
在实践中,html
策略只会更改在 HTML 中具有特殊含义的字符,而 html_attr
策略会替换几乎所有非字母数字字符,包括空格。看例子:
看到这个文本,好吗?
raw: See this <b>text</b>, OK?
html: See this <b>text</b>, OK?
html_attr: See this <b>text</b>, OK?
据我了解,对于HTML,你可以使用html
策略,对于XML文档,你最好使用html_attr
策略,但我没有在实践中尝试过.
关于php - Twig 中 escape ('html' ) 和 escape ('html_attr' ) 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12038048/