Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get javascript variable's value in Django url template tag

It is known that there's a DRY way of directing to an URL by using django template tag "url", say

{% url "someview" arg1=X %} 

Here, I want "X" to be the value of a javascript variable, say tmp. But the following doesn't work

<script>     ...{% url "someview" arg1=tmp %}... </script> 

How should I get the value inside a template tag?

like image 972
Mike Lee Avatar asked Jul 24 '13 11:07

Mike Lee


People also ask

Can you use JavaScript in Django template?

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.

What does form {% url %} do?

{% url 'contact-form' %} is a way to add a link to another one of your pages in the template. url tells the template to look in the URLs.py file. The thing in the quotes to the right, in this case contact-form , tells the template to look for something with name=contact-form .

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What is URL tag in Django?

The URL template tag is a typical type of Tag in the Django Template Language framework. This tag is specifically used to add View URLs in the Template Files.


1 Answers

I found a trick that might work under most circumstances:

var url_mask = "{% url 'someview' arg1=12345 %}".replace(/12345/, tmp.toString()); 

It's clean, and it doesn't break DRY principle.

like image 54
Mike Lee Avatar answered Sep 18 '22 11:09

Mike Lee