Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a JS variable within a Django template tag

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?

like image 818
Brian D Avatar asked Jul 12 '11 22:07

Brian D


People also ask

How do I declare a variable inside a Django template?

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.

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.

How add JS file in Django?

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.


1 Answers

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);
like image 123
tcarobruce Avatar answered Sep 30 '22 17:09

tcarobruce