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?
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.
{% 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 .
{% %} 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With