Use Django template tags in jQuery/Javascript?

前端 未结 3 630
轻奢々
轻奢々 2020-11-29 07:28

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

相关标签:
3条回答
  • 2020-11-29 07:55

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

    0 讨论(0)
  • 2020-11-29 08:11

    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

    0 讨论(0)
  • 2020-11-29 08:12

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

    0 讨论(0)
提交回复
热议问题