Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include multi-line html from django template into javascript variable

From a Django template, I would like to include an html snippet from a file, say mysnippet.html:

<div>
    blah
</div>

into a javascript variable:

<script type="text/javascript">
     var myvar = {% include 'mysnippet.html' %}
</script>

The problem is that the new lines would need to be escaped. Otherwise, Javascript complains for "unterminated string literal".

I know slashes can be added with {{x|addslashes}} but I don't know how to do it for the {% include %} tag.

like image 570
gozzilli Avatar asked Apr 03 '11 00:04

gozzilli


1 Answers

have you tried filter template tag?

{% filter addslashes %}{% include 'mysnippet.html' %}{% endfilter %}

better escape of all special characters is to use escapejs filter:

{% filter escapejs %}{% include 'mysnippet.html' %}{% endfilter %}
like image 110
Jerzyk Avatar answered Oct 04 '22 20:10

Jerzyk