Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace break lines in twig

Tags:

replace

twig

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…

like image 675
sh3211 Avatar asked May 07 '12 19:05

sh3211


4 Answers

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.

like image 187
Nick F Avatar answered Nov 16 '22 18:11

Nick F


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

like image 23
Yann Chabot Avatar answered Nov 16 '22 17:11

Yann Chabot


There is nl2br filter: http://twig.sensiolabs.org/doc/filters/nl2br.html

like image 12
Wojciech Jasiński Avatar answered Nov 16 '22 16:11

Wojciech Jasiński


Use {{ post.content | nl2br }}

like image 9
Anwar Abdelkabir Avatar answered Nov 16 '22 16:11

Anwar Abdelkabir