javascript - 在 Javascript/jQuery 中无法检索 Django 模板变量值

标签 javascript jquery django django-templates

当我做这样的事情时:

$("#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/

相关文章:

javascript - 用于保护允许用户上传样式的网站的沙盒

javascript - jQuery 在多个元素上调用函数的更好方法?

python - Tasty-Pie - 在不使用 full=True 的情况下拉入相关领域?

javascript - 需要一些关于 jQuery DOMready 的解释

javascript - 在javascript中动态解析json对象

python - Django 表单不工作

python - 为数据库对象获取半长唯一 ID(非顺序)键的最佳方法是什么

javascript - jQuery 插件中的私有(private)变量

javascript - 如何在 Python 中生成随机字母数字字符串?

javascript - 使用 GLTF 的一部分作为 InstancedMesh