Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Django template {{Variable}} from JavaScript

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.

like image 789
Dipak Avatar asked Jul 27 '10 03:07

Dipak


People also ask

What does {{ name }} this mean in Django templates?

8. What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.

Can Django template be used in JavaScript?

Adding JavaScript to Our Django TemplateWe can add JavaScript to our template using an inline <script> tag or an external JavaScript file. Let's create a app. js file, put it in a js folder that you need to create in the static folder of your application.

How do I access Django templates?

To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.

How do you pass variables from Django view to a template?

And this is rather simple, because Django has built-in template modules that makes a transfer easy. Basically you just take the variable from views.py and enclose it within curly braces {{ }} in the template file.


2 Answers

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.

like image 66
Pointy Avatar answered Oct 18 '22 10:10

Pointy


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 }};
like image 5
Jason Prado Avatar answered Oct 18 '22 10:10

Jason Prado