Question

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".

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top