Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Django template tags in jQuery/Javascript?

Tags:

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

like image 874
john2x Avatar asked May 15 '11 14:05

john2x


People also ask

Can I use Django template tags in JavaScript?

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.

How do I use template tags in JavaScript?

You can use the <template> tag if you have some HTML code you want to use over and over again, but not until you ask for it. To do this without the <template> tag, you have to create the HTML code with JavaScript to prevent the browser from rendering the code.

How do I use custom template tags in Django?

Create a custom template tagUnder the application directory, create the templatetags package (it should contain the __init__.py file). For example, Django/DjangoApp/templatetags. In the templatetags package, create a . py file, for example my_custom_tags, and add some code to it to declare a custom tag.


1 Answers

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

like image 76
dr jimbob Avatar answered Sep 27 '22 20:09

dr jimbob