How to pass javascript variable to django custom filter
Asked Answered
L

1

6

Is there a way to access a JavaScript variable in django template code as shown below:

var tags_v1 = '{{ form.tags_1.value }}';
tags_v1 = tags_v1.split('{{ form.value_delim }}');
tags_v1 = tags_v1.map(function (item) { return '{{ $(item)|get_tag }}'; }) ;

I want to pass the value of "item" as variable to the custom filter "get_tag".

Lynea answered 6/1, 2014 at 14:30 Comment(0)
Y
38

There is an important distinction between Django template code and in-browser JavaScript that you seem to be missing:

Django templates are built on the server side, while JavaScript executes on the client side.

That means that template code is always executed before JavaScript (as it is executed by the server before the page is sent to the client). As a consequence, it is impossible to mix JavaScript and Django code the way you want to.

For example, you seem to think that Django code inside JavaScript loop would execute multiple times. That, of course, is not true. Django code is executed once, on the server side, without any regard for JavaScript which is executed later in the browser (i.e., on a different machine!). For Django, your JavaScript code is just a meaningless text.

So, the answer is: if you want to split a string and apply a Django filter to each item, you need to split the string on the server side in Django. You can't split it in JavaScript and then manipulate the resulting list in Django, because Django runs much earlier, and on a different computer.

Yalonda answered 6/1, 2014 at 14:56 Comment(2)
What do you mean @J0ANMM? Every single world of this post is still valid, even if you use AJAX.Yalonda
I just wanted to point out that with AJAX you can go back to the server side after being on the client side. Anyway, quite often this approach might be overcomplicating things, but I thought it is good to keep it in mind.Boulware

© 2022 - 2024 — McMap. All rights reserved.