[英]best practice including javascript in django template
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? 我应该只使用<script src=".."
还是链接ref =“ ..”来添加JavaScript文件? Which is the better way? 哪个更好?
Use <script src="yourscript.js"></script>
as usual, without the include
template tag. <script src="yourscript.js"></script>
使用<script src="yourscript.js"></script>
,而不使用include
模板标记。
Django include
template tag is not meant to load JavaScript source. Django include
template标签并不意味着加载JavaScript源。 It is used to include a sub template whose markup can access the template context of the including template . 它用于包含一个子模板 ,该子模板的标记可以访问包含模板的模板上下文。 Read here . 在这里阅读。
I know this question is 6 years old, and the answer is an exact answer for the question. 我知道这个问题已有6年历史了,答案是对这个问题的确切答案。 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. 但是以某种方式,这在我的google搜索结果中对我来说非常重要,我想我会在这里发布更多信息,以帮助像我这样的人寻找最佳实践。 Use template inheritance, and blocks for content, css and javascript. 使用模板继承,并阻止内容,css和javascript。
Docs: 文件:
https://docs.djangoproject.com/en/2.0/ref/templates/language/#template-inheritance https://docs.djangoproject.com/zh-CN/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块中:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.