gpt4 book ai didi

django:我可以在 html 模板中编写 python 吗?

转载 作者:行者123 更新时间:2023-12-02 06:10:05 25 4
gpt4 key购买 nike

{% if request.session["user_name"] %}
<div class="abcd">user has username</div>
{% else %}
<div class="abcd">user doesn't has username</div>
{% endif %}

这是违法的吗?有错误:

TemplateSyntaxError at /users/register/submit

Could not parse the remainder: '['user_name']' from 'request.session['user_name']'

最佳答案

Django 文档说:

Django template system is not simply Python embedded into HTML

这意味着您不能编写 Python。

但是谈论变量,doc还说:

Behind the scenes

Technically, when the template system encounters a dot, it tries the following lookups, in this order:

  • Dictionary lookup
  • Attribute lookup
  • Method call
  • List-index lookup

这意味着您正在尝试的是可能的,但正确的语法是:

{% if request.session.user_name %}

关于django:我可以在 html 模板中编写 python 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4094135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com