Use Django template tags in jQuery/Javascript?

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 %}.

Leave a Comment