I want to fill a JavaScript array with values from PHP variables using TWIG.
<script type="text/javascript">
var cont=new Array();
{% for key, post in posts %}
cont[{{ key }}] = "{{ post.content }}";
{% endfor %}
</script>
The problem is that I have post
variable with several lines, so the above code make JS commands separated to few lines, that is translated as several commands, and I have an error.
So I think that I need to replace all the 'new lines' to "\n".
I tried to do like this:
cont[{{ key }}] = "{{ post.content | replace({"\n":"<br>"}) }}";
But it does not help. It still stay as few lines…
For a similar problem (outputting user data into Javascript), I found the following was necessary:
post.content|replace({"\n":' ', "\r":' '})
ie. replace \r
as well as \n
with spaces. This is because some user-entered content (especially for users on Windows) may contain \r
(carriage returns) as well as line-breaks, which it seems do still break Javascript if not removed.
For me, nl2br wasn't suitable, because I was feeding the user content into a Javascript method (for adding user-inputted addresses to a Google Map, for what it's worth), so I didn't want any line breaks, HTML or otherwise.
The best way (and good way) to write some javascript using Twig (if you don't want \r\n
) is this way:
{{ example|e('js') }}
Replacing <br />
can, of course, work, but you will encounter other problems in javascript using data from your data. Using javascript escape, it will perfectly write valid javascript the way you'd expect it to do.
For more information about escape filter:
https://twig.symfony.com/doc/3.x/filters/escape.html
There is nl2br filter: http://twig.sensiolabs.org/doc/filters/nl2br.html
Use {{ post.content | nl2br }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With