MicWit MicWit - 1 month ago 14
Twig Question

Including a Twig template in a JQuery .html() call and remove new lines

I want to create a dialog box that will be the content of another Twig file. So in the JQuery call, I have:

$('<div></div>')
.html('{% include "folder/file.html.twig" %}')
.dialog({....


In file.html.twig there are new lines, so when placed into the .html call it fails as the .html call doesn't allow for new lines. If there was a way to use the replace from Twig to get rid of all new lines that may work, however, when I use:

$('<div></div>')
.html('{% include "folder/file.html.twig"|replace({"\n":""}) %}')
.dialog({....


it replaces any new lines (that don't exist) out of the path, not the rendered content.

Answer

Use the spaceless tag. It gets rid of all whitespace, so your code and content will not be affected, but it will all display in one line:

$('<div></div>')
    .html('{% spaceless %}{% include "folder/file.html.twig" %}{% endspaceless %}')
    .dialog({....

See http://twig.sensiolabs.org/doc/tags/spaceless.html for more info.

Comments