简体   繁体   中英

How to use django template syntax in static files

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?

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 eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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