user1032531 user1032531 - 4 months ago 13
Twig Question

Prevent quotes from being converted to HTML entities in twig ternary operator

The following does not convert the quotes to HTML entities

{% for row in files %}
<tr data-id="{{ row.id }}"><td>{{ row.name }}</td></tr>
{% endfor %}


The following does convert the quotes to HTML entities

{% for row in files %}
<tr{{ row.id?' data-id="'~row.id~'"' }}><td>{{ row.name }}</td></tr>
{% endfor %}


How can I prevent quotes from being converted to HTML entities in a twig ternary operator?

Answer

You should try the |raw filter (check out the documentation). This is because in general, everything that twig prints out will be escaped to avoid things like cross-site-scripting. An exception is made for entirely static values like {{ '<b>static value</b>' }} which will not be escaped.

In your case, the following should work:

{% for row in files %}
  <tr{{ (row.id?' data-id="'~row.id~'"')|raw }}><td>{{ row.name }}</td></tr>
{% endfor %}
Comments