[Django]-Use Django template tags in jQuery/Javascript?

36👍

Yes, I do it frequently. Your javascript has to be served through django, but if you just have it in the html header as inline javascript you’ll be fine.

E.g: I use this to put prefix on a dynamic formset I use.

{% extends "base.html" %}
{% block extrahead %}
<script type="text/javascript">
$(document).ready(function() {
    {# Append fields for dynamic formset to work#}
    {% for fset, cap, _, tid in study_formsets.fset_cap_tid %}
        $(function() {
            $('.form_container_{{ tid }}').formset({
                        prefix: '{{ fset.prefix }}',
                        formCssClass: '{{ tid }}',
                        extraClasses: ['myrow1', 'myrow2']
                    });
        });
    {% endfor %}
});
</script>
{% endblock %}

Note in “base.html” I have a html head where the jquery libraries are loaded, that contains {% block extrahead %}{% endblock %}.

15👍

You can’t use Django’s template tags from your Javascript code if that’s what you mean. All the Django variables and logic stop existing after the template has been rendered and the HttpResponse has been sent to the client. At that moment when Javascript executes, the client (browser) has no notion the variables you rendered the template with (such as “form”).

What you can do is have Javascript modify your HTML page using chunks of HTML that were rendered by your Django template.

If you want to generate HTML on client side, I’d recommend to look at client side tempalte libraries (eg. JQuery Templates – use those with the {% verbatim %} templatetag).

👤Jj.

0👍

If you want to use variables inside your rendered javascript I (that’s my opnion), think it’s a bad idea. But if all you want is to generate URL for your views, media and static files, I do this a lot.

Take a look to this github: jscssmin

-1👍

Yes, you can use`

Example : `{{ user.username }}`

Be sure this is not single quotes but ‘(back tick / back quote)

Leave a comment