How to use django template syntax in static files

放肆的年华 提交于 2019-12-11 04:14:35

问题


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.

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

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

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>

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

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?


回答1:


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>

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



来源:https://stackoverflow.com/questions/54495148/how-to-use-django-template-syntax-in-static-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!