Since version 1.9.0, Twig provides the html_attr
strategy for the escape
filter (see documentation).
The html
strategy uses the htmlspecialchars PHP function (this is confirmed by a quick look at the source). The html_attr
strategy uses a series of custom substitutions that seem to have the same effect eventually.
Is there a difference between the two strategies?
The source says:
/*
* 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
*/
In practice, the html
strategy only changes the characters that have a special meaning in HTML, while the html_attr
strategy replaces nearly all non-alphanumeric characters, including spaces. See the example:
See this text, OK?
raw: See this <b>text</b>, OK?
html: See this <b>text</b>, OK?
html_attr: See this <b>text</b>, OK?
In my understanding, for HTML, you can use the html
strategy, for XML documents, you better use the html_attr
strategy, but I have not tried this in practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With