How to embed double quotes in Twig interpolation?

11,109

Solution 1

If you want to include " you need to escape the character

{{ " href=\"#{value1}#{value2)\"" }}

But it's not a good idea

A better way is to include your value directly in the attribute like :

<a href="{{url}}">Some link</a>

And of course, you can use concatenation

<a href="{{value1~value2}}">Some link</a>

Solution 2

The best solutions is :

href="{{value1}}{{value2}}"

Doing so, both value1 and value2 will safely be escaped regarding HTML special characters. And your double quotes will directly be outputed.

Why your method is bad practice :

What you want to do is (these two are equivalent) :

{{ " href=\"#{value1}#{value2}\"" }}

Or

{{ ' href="'~value1~value2~'"' }}

Doing it so, it will escape the href double quotes and integrate them in the concatenation.

But since the concatenation is in {{ ... }} twig will also escape every resulting double quotes with the HTML autoescape, they will be replaced with &quot;.

You could disable this html autoescaping so :

{{ 'href="'~value1~value2~'"' | raw}}

But then it is dangerous, because value1 and value2 won't be html escaped anymore, and you will be exposed to XSS injections.

Share:
11,109
GazleyGeester
Author by

GazleyGeester

Updated on June 04, 2022

Comments

  • GazleyGeester
    GazleyGeester almost 2 years

    I am trying to replace sprintf(' href="%s%s"', ..., ...) from a PHP file into its Twig alternative. I'd like to use Twig's interpolation feature but, the string expression has to be wrapped in double-quotes and contains embedded quotes surrounding the href attribute values.

    Is there a way to do this? The docs seem fairly light weight in this regard.

    {{ " href="#{value1}#{value2)"" }}