Reputation: 3311
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?
Upvotes: 1
Views: 569
Reputation: 389
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.
Upvotes: 3