28

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

1
  • 2
    i guess you'll know when you try it :) Commented May 15, 2011 at 14:17

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

5 Comments

Is there any modern way how to do this? Mixing javascript in html is not fully unobtrusive..
@Mejmo - Well, you could have your javascript file served dynamically by django (e.g., draft up a template for the js file, generate a view for it, add it to your urls.py). Granted, this likely will be less efficient and probably less manageable than inline JS (each page load requires two dynamically processed files) -- unless you need the same dynamic JS in many templates. Really, the best method is to have static JS files, which manipulate data from the DOM (possibly initially hidden) or dynamically served in json data. If you need template tag logic in JS, write it in JS.
Please check this out; <script> $(document).ready(function(){ $('#delete').submit.function(e){ e.preventDefault(); var station_id = {{ station.id }} $.ajax({ type: 'POST', url: '/station/' + station_id, headers: {'X_METHODOVERRIDE': 'DELETE'} }); }); }); </script> You see any reason for my using of Django's template language inside this script (var station_id = {{ station.id }}) not to work.
Please check out stackoverflow.com/questions/30461839/… I have the problem specific there. Especially see the update.
was originally using just plain {{template_tags}} without putting ' ' around them, but saw your solution and that fixed my issues. So if you're using template tags in JQuery, don't forget to enclose them in single quotes!
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).

Comments

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

Comments

-1

Yes, you can use`

Example : `{{ user.username }}`

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.