[英]Loading JavaScript files selectively in Django
I have Post
model for a blog app in Django. 我在Django中有一个博客应用程序的
Post
模型。 It has a field named body
. 它有一个名为
body
的字段。 In posts, I may use Latex so I need to use MathJax.js
. 在帖子中,我可能会使用Latex,所以我需要使用
MathJax.js
。 In some posts, I add code snippet, so I use highlight.js
. 在某些帖子中,我添加了代码段,因此我使用
highlight.js
。 In some I use both, in some I use none of them. 在某些情况下我会同时使用它们,在某些情况下我不会使用它们。
I want to load the relevant javascript depending on the body
field of the Post
model (similar to THIS ). 我想根据
Post
模型的body
字段加载相关的javascript(类似于THIS )。 How can I make the relevant .js file(s) to load automatically? 如何使相关的.js文件自动加载?
I know that I can add an indicator field like hasLatex
( True
, False
) or hasCode
( True
, False
). 我知道我可以添加一个指标字段,例如
hasLatex
( True
, False
)或hasCode
( True
, False
)。 But I'm lazy, I want Post.body
to be automatically scanned and only relevant js files loaded. 但是我很懒,我想自动扫描
Post.body
并且只加载相关的js文件。
Set something in your context or use a template context processor. 在您的上下文中设置某些内容或使用模板上下文处理器。 For example I load code that handles forms if there is a
form
key is my context. 例如,如果上下文中有
form
键,那么我将加载处理表单的代码。 For something I want on almost every page I put a no_something in my context to disable it. 对于几乎所有页面上我想要的东西,我在上下文中添加了no_something来禁用它。 This is done by putting a conditional around the tag in your base template.
这是通过在基本模板中的标记周围放置条件来完成的。 If the variable is not there or is false it won't show.
如果变量不存在或为false,则不会显示。
What I also do is put my static files in lists inside of my context. 我还要做的是将我的静态文件放在上下文中的列表中。 JavaScript is in
context['js']
and css in context['css']
. JavaScript在
context['js']
而CSS在context['css']
。 Those are looped through in my header. 这些在我的标题中循环。 I can implement get_context_data in a base class, and all the views that extend from that will have the javascript and css files.
我可以在基类中实现get_context_data,从此扩展的所有视图都将具有javascript和css文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.