How to replace break lines in twig
replace, twig
Solution
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.
Problem
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…