【问题标题】:using django template logic in loaded JS files (integrate django JS)在加载的 JS 文件中使用 django 模板逻辑(集成 django JS)
【发布时间】:2015-11-04 10:48:42
【问题描述】:

我有一个 JS sn-p 可以在多个文件中工作和使用:

<script>
{% if not articles %}
    var url = {% url 'index:new-article' %};

    $('body').on('click',function(e){
        window.location = url
    });
    ;
{% endif %}

</script>

但是,如果我将该代码放在单独的文件“main.js”中并将其加载到模板中,它将不再起作用。它现在在'main.js'中:

var url = {% url 'index:new-article' %};

$('body').on('click',function(e){
    window.location = url
});
;

但是当像这样加载时:

{% if not articles %}
    <script src="media/js/main.js"></script>
{% endif %}

在“mytemplate.html”中,代码​​现在已损坏。其他人建议简单地将您想要使用的 JS 文件包含在您的 django 模板中 (best practice including javascript in django template)。如何使用一些模板逻辑,例如“如果不是这个,请包含 js 文件”并使其工作?谢谢

【问题讨论】:

  • @cody4321 “代码现在已损坏”到底是什么意思?它是否返回错误?
  • 点击 body 元素不再打开窗口。我进入 Chrome JS 控制台并没有看到任何错误。你用什么工具来查看错误?我永远不知道为什么 JS 会崩溃

标签: javascript jquery python django templates


【解决方案1】:

{% url 'index:new-article' %} 将返回原始字符串,您必须引用其输出才能使其成为有效的 Javascript。

<script>
{% if not articles %}
    var url = '{% url 'index:new-article' %}';

    $('body').on('click',function(e){
        window.location = url
    });
    ;
{% endif %}

</script>

【讨论】:

  • 谢谢弗兰克,我会尽快检查这是否是唯一的问题
猜你喜欢
  • 2016-09-28
  • 1970-01-01
  • 2015-09-21
  • 1970-01-01
  • 1970-01-01
  • 2015-05-05
  • 2018-12-30
  • 2012-02-27
  • 2017-09-05
相关资源
最近更新 更多