Reputation: 49
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)"" }}
Upvotes: 3
Views: 16878
Reputation: 3135
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 "
.
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.
Upvotes: 7
Reputation: 8461
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>
Upvotes: 7