3

I am using short conditional to discriminate the values ​​displayed in a list of records.

For example if I want the name of the customers who have a greater than 100 identifier are emphasized (<em> </em>) perform the following:

{# Displays the identifier of the client #}
{% set strClient = '<em>' ~ client.name ~ '</em>' %}
{{ Client.id > 100 ? strClient|raw : client.name }}

Here the HTML is processed by the browser and customer name is displayed emphasized, the fact is that if for example you want to show your phone, which can be null or not, and if it is no display a message emphasized; I perform the following:

{# Displays the customer phone or message if there #}
{{ Client.id > 100 ? client.tel : '<em> Not found </em>' }}

In the latter case HTML tags are not processed by the browser and displayed as plain text, I also tried the following:

{# Displays the customer phone or message if there #}
{{ Client.id > 100 ? client.tel : '<em> Not found </em>'|raw }}

And this one:

{# Displays the customer phone or message if there #}
{% set strClient = '<em> Not found </em>' %}
{{ Client.id > 100 ? client.tel : strClient|raw }}

With the same result, ie when is a string, this stored in a variable or do not get the HTML tags that always appear as if it were processed plaintext.

Does anyone know how to get the HTML string in a twig be interpreted?

lalitpatadiya
  • 720
  • 7
  • 21
JSGarcia
  • 556
  • 7
  • 18
  • 1
    From the twig doc, Twig does not escape static expressions: http://twig.sensiolabs.org/doc/tags/autoescape.html – Med Jun 04 '15 at 11:35

2 Answers2

4

When using the raw filter with a tenary if you need to wrap the whole statement in brackets for it to work.

E.g. {{ (Client.id > 100 ? client.tel : '<em> Not found </em>')|raw }}

Rooneyl
  • 7,802
  • 6
  • 52
  • 81
  • Thanks,**works perfectly**. Quick and very clean solution, without having to put more blocks. **Greetings friend** :) – JSGarcia Jun 04 '15 at 11:46
2

In my tests on your example, none of the attempts worked, including your first example:

{# Displays the identifier of the client #}
{% set strClient = '<em>' ~ client.name ~ '</em>' %}
{{ Client.id > 100 ? strClient|raw : client.name }}

However, if you wrap your examples with {% autoescape false %} and {% endautoescape %}, this should solve the issue. All of your examples should display as expected if wrapped like this:

{% autoescape false %}
{# Displays the customer phone or message if there #}
{{ Client.id > 100 ? client.tel : '<em> Not found </em>' }}
{% endautoescape %}

No need for |raw if using autoescape.

Kristen Waite
  • 1,385
  • 2
  • 15
  • 28
  • This solution also **works** but it seems that much dirty code having to be opening and closing blocks, anyway thank you very much for answering. **Greetings friend** :) – JSGarcia Jun 04 '15 at 11:47