john2x
john2x

Reputation: 23634

Use Django template tags in jQuery/Javascript?

Can I use Django's template tags inside Javascript? Like using {% form.as_p %} in jQuery to dynamically add forms to the page.

Upvotes: 28

Views: 39055

Answers (4)

Ashutosh Gupta
Ashutosh Gupta

Reputation: 31

Yes, you can use`

Example : `{{ user.username }}`

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

Upvotes: -1

Gustavo Vargas
Gustavo Vargas

Reputation: 2597

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

Upvotes: 0

Jj.
Jj.

Reputation: 3160

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).

Upvotes: 15

dr jimbob
dr jimbob

Reputation: 17711

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

Upvotes: 36

Related Questions