10

I tried to access django template variable in html page inline javascript, it works fine. But if I include js using <script src="..> then it dont work. Is this limitation or I'm doing something wrong? I really appreciate your help.

2 Answers 2

12

The included Javascript isn't processed by the Django template processor on the server, so that won't work. If you need to pass information through the template to included Javascript files, have your template create a small <script> block wherein some global variable is declared to contain those template variables. Then, your pure Javascript file can get the values by looking for the global object created by that <script> from the template.

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

Comments

5

Pointy's answer is correct. I often find this filter useful for that situation:

@register.filter(name='json')
def _json(obj):
  #remember to make sure the contents are actually safe before you use this filter!
  return safestring.mark_safe(json.dumps(obj)) 

then in a <script> tag I can just do something like this:

window.g_details = {{ details|json }};

2 Comments

@JasonPrado : Why should one do this?
This answer is 4 years old so I bet django has a better solution by now. But my idea here was that it is nice to be able to convert a python dictionary into a JSON dictionary safely and easily.

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.