1

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Okay. Thanks you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.