Home > Mobile >  How to use javascript variable in django if statement (template)?
How to use javascript variable in django if statement (template)?

Time:03-26

I'm trying to update my html element with django if statement:

element.innerHTML= `{% if person.name == ${value} %} something {% endif %}`

but I receive an error:

TemplateSyntaxError at /
Could not parse the remainder: '${value}' from '${value}'

I also tried:

 `{% if person.name == ${value} %} something {% endif %}`

But the statement doesn't work properly. Is there anything I can do to combine javascript with Django variables?

CodePudding user response:

Short Answer
No. You can not do this, at least not that easily.

Detailed (slightly) Answer
Django replaces all tags, {{ }} and {% %} with the result at the server (back end) end when the page is rendered, before it gets to the client. Your JavaScript (JQuery?) variable is evaluated by the client (the front end). Django will not know what ${value} is. So, no, you can not use a JavaScript variable in Django template code.

This does not mean you can not achieve what you want, but it must be done in the following way. Your JavaScript code can fetch the value of person.name from a view and then you can do your if statement in the JavaScript file after the response from the fetch is received. The view could return the value of person.name as a JsonResponse

  • Related