first off I am well aware that twig is server- and JavaScript is clientside.
Still I would like to use twigs path()
function within JavaScript and inject an Javascript variable as a RAW-String, but it gets escaped all the time and I am curious why the raw-filter does not apply?
I do have the following Javascript within my twig file (simplified):
// file.html.twig
<script>
print '<a href="{{ path('article_edit', {id: ("' + full['id'] + '"|raw)}) }}">Linktext</a>';
</script>
As the path for article_edit
is /articles/{id}/edit
, my expected serverside-output would be:
// Expected twig-render
<script>
print '<a href="/articles/' + full['id'] + '/edit">Linktext</a>';
</script>
Which would be rendered on clientside to <a href="/articles/1/edit">Linktext</a>
But still, even though I used the |raw
filter, twig does escape the string. Resulting in the following output:
// Actual twig-render
<script>
print '<a href="/articles/%27%20+%20full%5B%27id%27%5D%20+%20%27/edit">Linktext</a>';
</script>
Why is twig ignoring the filter and does escape the JavaScript? Isn’t that what that filter is for, so I could built up an dynamic Javascript code within twig?
Also I can not build up the id within PHP as the id comes from another AJAX call. I currently use the hardcoded path as a workaround, but I am curious why the filter is ignored…
Thanks for any help