如何在静态文件中使用Django模板语法 [英] How to use django template syntax in static files

查看:41
本文介绍了如何在静态文件中使用Django模板语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django模板中包括静态文件有很多可用的文档.但是,我找不到有关如何在静态文件中使用Django模板语法的任何信息.

There is a lot of documentation available in including static files in Django templates. However, I cannot find anything on how to use Django template syntax in static files.

我有一个HTML文件,其中在这样的标记之间包含了javascript:

I had an html file that included javascript between tags like this:

var nodes = JSON.parse('{{nodes|safe}}');

我现在将所有JavaScript都移到了我要提供的静态.js文件中.它包含在HTML文件中,如下所示:

I now moved all the javascript to a static .js file which I'm serving. It is included in the HTML file like this:

<script src="{% static 'citator/analysis.js' %}" type="text/javascript"></script>

除了.js文件中使用Django模板语法的部分之外,其他所有内容都运行正常.

Everything runs fine except for the parts of the .js file which use the Django template syntax.

我的问题是,如果javascript不是直接在模板中而是作为静态文件并导入的,有没有办法在javascript中使用Django模板语法?还是我必须在模板中获取上下文数据,然后将其传递给静态文件中的函数?

My question is, is there a way to use Django template syntax in the javascript if the javascript is not directly in the template, but served as a static file and imported? Or do I have to get the context data in the template, and then pass it to functions in the static file?

推荐答案

不幸的是,没有任何Django功能可让您直接执行此操作.阻止此情况的基本问题是将上下文传递到视图中 render()函数中提到的模板(或其他行为相同的函数,例如 render_to-response()).最好的选择是在模板文件中使用内联js.可以理解,为了保持代码的清洁,您不希望模板中包含js函数.因此,像这样获取所需的数据:

Unfortunately, there isn't any Django feature that allows you to do this directly. The fundamental issue that prevents this is that context is passed to the template that is mentioned in your render() function in the view(or any other function the behaves the same way e.g. render_to-response()). The best option here would be to use inline js in your template file. Understandably, to keep your code clean, you would not want your js functions in your template. So, get the data you want like so:

<script>
    var nodes = JSON.parse('{{nodes|safe}}');
</script>

在此代码之后 导入您的静态js文件,您应该一切顺利,并保持代码的干净和模块化.

import your static js file after this code and you should be good to go, keeping your code clean and modular.

这篇关于如何在静态文件中使用Django模板语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆