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

21👍

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 %}
👤Jerzyk

2👍

Following Jerzyk suggestion (thanks!), I’ve used

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

Unfortunately I realised that it doesn’t escape new lines as I thought, but quotes. So I defined a new filter:

def escapenewline(value):
    """
    Adds a slash before any newline. Useful for loading a multi-line html chunk
    into a Javascript variable.
    """
    return value.replace('\n', '\\\n')
escapenewline.is_safe = True
escapenewline = stringfilter(escapenewline)

register.filter('escapenewline', escapenewline)

And used it instead of addslashes:

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

On the Django docs there is a how-to on custom templates.

1👍

I noticed that you are using javascript. If you don’t mind using jQuery and some AJAX along with it, there is an alternate way to assign html to a javascript variable.

Create a view to display your snippet:

# views.py
def mysnippet(request):
    return render(
        request,
        'yourapp/mysnippet.html',
    )

# urls.py
urlpatterns = patterns('yourapp.views',
    url(r'mysnippet/$', 'mysnippet', name='mysnippet'),
)

You can place the following in your template or separate the javascript in its own file:

<script type="text/javascript">
$(document).ready(function() {
    $.get("/yourapp/mysnippet/", function(data) {
        var myvar = data;
    });
});
</script>

myvar should now contain the html, the new lines don’t need to be escaped in that case.

Leave a comment