{% 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/