Can I use Django's template tags inside Javascript? Like using {% form.as_p %}
in jQuery to dynamically add forms to the page.
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.
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.
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.
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 %}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With