如何在 Flask/Jinja 模板中以不同于过滤器的方式使用管道?
How to use pipe in Flask/Jinja template differently than filters?
我正在使用 Flask with the Jinja2 templating engine to build a website. As an ORM I use the (excellent) Peewee ORM,现在 运行 遇到了问题。
在我的 Flask 视图中,我从数据库中获得了一个用户列表:
@app.route('/stats')
def stats():
users = User.select()
return render_template('stats.html', users=users)
在我的模板中,我遍历了用户并尝试扩展查询。这有效:
{% for user in users %}
{{ user.app_logs.where(AppLog.type == 'LOGIN').first().created }}
{% endfor %}
但是这个:
{% for user in users %}
{{ user.app_logs.where((AppLog.type == 'LOGIN') | (AppLog.type == AppLog.TICKET)).first().created }}
{% endfor %}
给出一个TemplateSyntaxError: expected token 'name', got '('
。我了解错误的来源:管道符号 (|
) 被定义为 a filter in Jinja。所以我尝试用反斜杠 (\|
) 转义它,但这不起作用。
所以我的问题是:有没有办法以某种方式转义管道符号,或者是否有人有任何其他想法来实现这一点?欢迎所有提示!
无论如何,最好保留模板 'dumb' 并在模板之外进行查询。在您的情况下,您可以使用 playhouse extension to use hybrid attributes on the model.
class User(Model):
...
@hybrid_property
def applog_login_ticket(self):
return self.app_logs.where((AppLog.type == 'LOGIN') | (AppLog.type == AppLog.TICKET)).first().created()
然后在您的模板中您可以这样做
{% for user in users %}
{{ user.applog_login_ticket }}
{% endfor %}
我正在使用 Flask with the Jinja2 templating engine to build a website. As an ORM I use the (excellent) Peewee ORM,现在 运行 遇到了问题。
在我的 Flask 视图中,我从数据库中获得了一个用户列表:
@app.route('/stats')
def stats():
users = User.select()
return render_template('stats.html', users=users)
在我的模板中,我遍历了用户并尝试扩展查询。这有效:
{% for user in users %}
{{ user.app_logs.where(AppLog.type == 'LOGIN').first().created }}
{% endfor %}
但是这个:
{% for user in users %}
{{ user.app_logs.where((AppLog.type == 'LOGIN') | (AppLog.type == AppLog.TICKET)).first().created }}
{% endfor %}
给出一个TemplateSyntaxError: expected token 'name', got '('
。我了解错误的来源:管道符号 (|
) 被定义为 a filter in Jinja。所以我尝试用反斜杠 (\|
) 转义它,但这不起作用。
所以我的问题是:有没有办法以某种方式转义管道符号,或者是否有人有任何其他想法来实现这一点?欢迎所有提示!
无论如何,最好保留模板 'dumb' 并在模板之外进行查询。在您的情况下,您可以使用 playhouse extension to use hybrid attributes on the model.
class User(Model):
...
@hybrid_property
def applog_login_ticket(self):
return self.app_logs.where((AppLog.type == 'LOGIN') | (AppLog.type == AppLog.TICKET)).first().created()
然后在您的模板中您可以这样做
{% for user in users %}
{{ user.applog_login_ticket }}
{% endfor %}