My django template boolean variable isn't working as expected in javascript
For what I see your auth_status
variable seems to be a string, not a boolean. A variable with a non-empty string on javascript will evaluate to true
on an if
clause.
Anyhow, something like
<script>
var auth_status = {{ user.is_authenticated }};
</script>
will not work because that will generate this HTML:
<script>
var auth_status = True;
</script>
As Python's True boolean is uppercased.
This should do the translation from Python to Javascript:
<script>
var auth_status = {{ user.is_authenticated|yesno:"true,false" }};
</script>
Check yesno docs here: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#yesno
Another option would be to use the jinja2 tojson
filter:
<script>
let javascript_var = {{ python_var|tojson }};
</script>
You may also want to use the safe
filter depending on what you're passing:
<script>
let javascript_var = {{ python_var|tojson|safe }};
</script>