在 jQuery/Javascript 中使用 Django 模板标签?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6008908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use Django template tags in jQuery/Javascript?
提问by john2x
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 的模板标签吗?就像{% form.as_p %}
在 jQuery 中使用动态添加表单到页面一样。
回答by dr jimbob
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.
是的,我经常这样做。您的 javascript 必须通过 django 提供,但是如果您只是将它作为内联 javascript 放在 html 标题中,那您就可以了。
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 %}
.
注意在“base.html”中,我有一个 html head
,其中加载了 jquery 库,其中包含{% block extrahead %}{% endblock %}
.
回答by Jj.
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").
如果这就是你的意思,你不能在你的 Javascript 代码中使用 Django 的模板标签。在呈现模板并将 HttpResponse 发送到客户端后,所有 Django 变量和逻辑都将停止存在。在 Javascript 执行的那一刻,客户端(浏览器)不知道您渲染模板所用的变量(例如“表单”)。
What you can do is have Javascript modify your HTML page using chunks of HTML that were rendered by your Django template.
您可以做的是让 Javascript 使用由您的 Django 模板呈现的 HTML 块来修改您的 HTML 页面。
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).
如果您想在客户端生成 HTML,我建议查看客户端模板库(例如JQuery 模板- 使用带有{% verbatim %} templatetag 的模板)。
回答by Gustavo Vargas
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.
如果您想在渲染的 javascript I(这是我的选项)中使用变量,则认为这是一个坏主意。但是,如果您只想为您的视图、媒体和静态文件生成 URL,我会经常这样做。
Take a look to this github: jscssmin
看看这个github:jscssmin