从版本1.9.0开始,Twig提供html_attr了escape过滤器的策略(参见文档).
该html策略使用htmlspecialchars PHP函数(通过快速查看源代码确认).该html_attr策略使用一系列自定义替换,最终似乎具有相同的效果.
这两种策略有区别吗?
在源说:
/*
* 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
*/
Run Code Online (Sandbox Code Playgroud)
在实践中,html策略仅更改HTML中具有特殊含义的字符,而html_attr策略几乎替换所有非字母数字字符,包括空格.看例子:
看到这个文字好吗?
raw: See this <b>text</b>, OK?
Run Code Online (Sandbox Code Playgroud)
html: See this <b>text</b>, OK?
html_attr: See this <b>text</b>, OK?
Run Code Online (Sandbox Code Playgroud)
在我的理解中,对于HTML,你可以使用html策略,对于XML文档,你最好使用html_attr策略,但我没有在实践中尝试过这个.