如果我有一个多次验证的模板{% if current_user.is_authenticated %}
那么使用这样的东西来最小化开销然后只检查current_user_is_authenticated
是有意义的?
{% if current_user.is_authenticated %}
{% set current_user_is_authenticated = True %}
{% else %}
{% set current_user_is_authenticated = False %}
{% endif %}
首先,这取决于如何在用户类上实现is_authenticated
方法。 默认情况下,如果当前用户已登录,它始终只返回True
。
回答您的问题:如果您没有自定义is_authenticated
方法实现,那么没有一件事可以最大限度地减少开销。但是,如果您在is_authenticated
中查询数据库、进行外部 api 调用等,那么在模板中多次使用它时将其返回值存储在变量中将是某种优化。