Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between escape('html') and escape('html_attr') in Twig

Tags:

php

escaping

twig

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?

like image 638
Laurent Pireyn Avatar asked Aug 20 '12 12:08

Laurent Pireyn


1 Answers

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 &lt;b&gt;text&lt;/b&gt;, OK?
html_attr: See&#x20;this&#x20;&lt;b&gt;text&lt;&#x2F;b&gt;,&#x20;OK&#x3F;

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.

like image 71
Harry Oosterveen Avatar answered Oct 27 '22 08:10

Harry Oosterveen