This one is a bit tricky for me. I've thus-far resorted to query parameters instead a variable within the {% url %}
tag, but I've just got to ask if it's doable:
I'd like to include a JS variable within my template tag. For example:
...
var foo = $(this).attr('title');
$('#bar').load("{% url app.views.view foo %}");
...
Can it be done?
Another approach to declare variables in the template is by using custom template tags. Create a custom template tag files named as custom_template_tags.py . Paste the below code in it. Now inside the HTML template use this custom template tag setvar to define a new variable.
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.
To load JavaScript file, just add the following line of code in index. html file. Run the server by using python manage.py runserver command. After that access the template by localhost:8000/index URL, and it will produce the following output to the browser.
Not doable. The HTML (and Javascript) are already rendered and served to the client by the time the Javascript is evaluated.
You need some other approach, like (as you mentioned) query parameters:
var foo = $(this).attr('title');
$('#bar').load("{% url app.views.view %}?foo=" + foo);
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