My django template boolean variable isn't working as expected in javascript

19,495

Solution 1

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

Solution 2

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>
Share:
19,495
Lucas Ou-Yang
Author by

Lucas Ou-Yang

More of my software at: http://github.com/codelucas Professionally, I'm a software engineer @Facebook and @Instagram

Updated on June 16, 2022

Comments

  • Lucas Ou-Yang
    Lucas Ou-Yang almost 2 years

    Here is the code in my base.html header

        <script>
            var auth_status = "{{ user.is_authenticated }}"
        </script>
    
        {% block scripts %}  {% endblock %}
    

    The rest of the scripts in my site are in the block scripts.

    In a child template (within the script block and within script tags) I have this code,

             if (auth_status) {
              //something
             }
    

    The error at hand is auth_status is always True, when it should be on and off depending on if the user is logged in. Request_context is being passed to the template so that should not be the error.

    Thanks