我的 django 模板布尔变量在 javascript 中没有按预期工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12395579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:05:19  来源:igfitidea点击:

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

javascriptdjangotemplates

提问by Lucas Ou-Yang

Here is the code in my base.html header

这是我的 base.html 标头中的代码

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

手头的错误是 auth_status 总是 True,什么时候应该打开和关闭取决于用户是否登录。 Request_context 被传递给模板,所以不应该是错误。

Thanks

谢谢

回答by Poli

For what I see your auth_statusvariable seems to be a string, not a boolean. A variable with a non-empty string on javascript will evaluate to trueon an ifclause.

对于我所看到的,您的auth_status变量似乎是一个字符串,而不是一个布尔值。与JavaScript的一个非空字符串变量将计算为true上的if条款。

Anyhow, something like

无论如何,像

<script>
    var auth_status = {{ user.is_authenticated }};
</script>

will not work because that will generate this HTML:

将不起作用,因为这将生成此 HTML:

<script>
    var auth_status = True;
</script>

As Python's True boolean is uppercased.

因为 Python 的 True 布尔值是大写的。

This should do the translation from Python to Javascript:

这应该完成从 Python 到 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

在此处检查 yesno 文档:https://docs.djangoproject.com/en/dev/ref/templates/builtins/#yesno

回答by TheDavidFactor

Another option would be to use the jinja2 tojsonfilter:

另一种选择是使用 jinja2tojson过滤器:

<script>
  let javascript_var = {{ python_var|tojson }};
</script>

You may also want to use the safefilter depending on what you're passing:

您可能还想safe根据传递的内容使用过滤器:

<script>
  let javascript_var = {{ python_var|tojson|safe }};
</script>