在 Django 模板中包含 javascript 的最佳实践
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10162247/
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
best practice including javascript in django template
提问by damon
Previously I used to do like this in a template
以前我曾经在模板中这样做
<html>
...
<script>
{% include "myapp/includes/jquery-1.7.1.min.js" %}
{% include "myapp/includes/myscript.js" %}
</script>
...
But this causes all the js code to be shown on the page source.
但这会导致所有 js 代码都显示在页面源上。
I am not using any Form in my template, so can I use Media class for adding js?
我没有在我的模板中使用任何 Form,那么我可以使用 Media 类来添加 js 吗?
Should I just use <script src=".."
or link ref=".." for adding javascript files? Which is the better way?
我应该使用<script src=".."
还是链接 ref=".." 来添加 javascript 文件?哪种方法更好?
回答by Joseph Victor Zammit
Use <script src="yourscript.js"></script>
as usual, without the include
template tag.
<script src="yourscript.js"></script>
像往常一样使用,没有include
模板标签。
Django include
template tag is not meant to load JavaScript source. It is used to include a sub templatewhose markup can access the template context of the including template. Read here.
Djangoinclude
模板标签不是为了加载 JavaScript 源代码。它用于包含一个子模板,其标记可以访问包含模板的模板上下文。在这里阅读。
回答by excyberlabber
I know this question is 6 years old, and the answer is an exact answer for the question. But somehow this came up for me so high in my google search results, I thought I would post additional info here, to help people like me, looking for best practice. Use template inheritance, and blocks for content, css and javascript.
我知道这个问题是 6 岁,答案是对问题的准确答案。但不知何故,这在我的谷歌搜索结果中对我来说是如此之高,我想我会在这里发布更多信息,以帮助像我这样的人,寻找最佳实践。使用模板继承和内容块、css 和 javascript。
Docs:
文档:
https://docs.djangoproject.com/en/2.0/ref/templates/language/#template-inheritance
https://docs.djangoproject.com/en/2.0/ref/templates/language/#template-inheritance
and a stackoverflow example, showing how to add another js file to the original js block using block.super:
以及一个 stackoverflow 示例,展示了如何使用 block.super 将另一个 js 文件添加到原始 js 块中: