在 jQuery/Javascript 中使用 Django 模板标签? [英] Use Django template tags in jQuery/Javascript?

查看:31
本文介绍了在 jQuery/Javascript 中使用 Django 模板标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在 Javascript 中使用 Django 的模板标签吗?就像在 jQuery 中使用 {% form.as_p %} 来动态添加表单到页面一样.

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

推荐答案

是的,我经常这样做.您的 javascript 必须通过 django 提供,但如果您只是将它作为内联 javascript 放在 html 标头中,您会没事的.

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

注意在base.html"中,我有一个 html head,其中加载了 jquery 库,其中包含 {% block extrahead %}{% endblock %}.

Note in "base.html" I have a html head where the jquery libraries are loaded, that contains {% block extrahead %}{% endblock %}.

这篇关于在 jQuery/Javascript 中使用 Django 模板标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆