简体   繁体   English

在外部JavaScript中使用Django模板标签

[英]using django template tags inside external JavaScript

我已经在我的html页面中包含了一个js文件(例如:application.js),但是我无法在该js文件中使用django模板标签,有没有办法直接在外部js文件中使用django模板标签?

Only if you will parse JS like a template. 仅当您像模板一样解析JS时。

If you need some variable inside JS (like STATIC_URL ), it is ok to use 如果您在JS中需要一些变量(例如STATIC_URL ),则可以使用

<script>window.staticUrl = "{{ STATIC_URL }}"</script>

or 要么

<html data-static-url="{{ STATIC_URL }}">

in your base template 在您的基本模板中

No, not if you include the application.js file as 不,如果您将application.js文件包含为

<script src="application.js"></script>

The template loader form Django will just render this to the final output of the html code. 模板加载器表单Django会将其呈现为html代码的最终输出。 The Django template tags/filters only render on template pages - they do not apply to external sources. Django模板标签/过滤器仅在模板页面上呈现-它们不适用于外部资源。

You could attempt to load the JavaScript file as text into the template. 您可以尝试将JavaScript文件作为文本加载到模板中。 So instead of referencing an external file, you would basically "paste" the code from the file into the template. 因此,基本上无需引用外部文件,而是将代码从文件“粘贴”到模板中。

You can serve your javascript as dynamic page. 您可以将JavaScript用作动态页面。 Create new django view to serve it (or use django.views.simple.direct_to_template) and use template with your actual javascript content. 创建新的django视图以提供服务(或使用django.views.simple.direct_to_template),并将模板与实际的javascript内容一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM