当我做这样的事情时:
$("#show").click(function(){
{% for p in collection %}
options.push({
'href' : '{{ p.id }}',
});
{% endfor %}
});
我可以检索 Django 模板变量的值。
然而,当我试图在其他部分做的时候:
$('[name=test]').live('click', function() {
alert('{{ current_state }}');
var msg = '<div class="userName"> {{ current_user }} </div>';
alert('Message' + msg);
});
我无法从中检索 Django 模板变量的值。
这里出了什么问题?我有时在 javasript/jQuery 中检索 Django 模板变量时遇到过这个问题。
编辑
当我在其他所有内容之上执行以下行时,整个 javasript 无法正常工作。知道为什么吗?
$('body').data('current_user_id', {{ current_user_id }});
$('body').data('current_user', {{ current_user }});
最佳答案
通常,JS 文件是完全静态的,因此,您不能将 Django 变量插入其中——它不能那样工作。
您可以采用的一种方法是让 Django 在呈现的 HTML 模板中“放置”JS 所需的变量,然后您可以获取它们并根据需要在 JS 代码中使用它们
例如,在您示例中使用 javascript 的模板中,添加:
<script type="text/javascript">
// attach variables from Django to the body node of the document
$('body').data('current_state', {{current_state}});
$('body').data('current_user', {{current_user}});
</script>
然后在您的 JS 中,从数据映射中提取值:
$('[name=test]').live('click', function() {
alert($('body').data('current_state'));
var msg = '<div class="userName">' + $('body').data('current_user') + '</div>';
alert('Message' + msg);
});
如果你不知道 $.data(),read this
关于javascript - 在 Javascript/jQuery 中无法检索 Django 模板变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8560665/