简体   繁体   English

仅使用jinja2而不使用Django的Django模板{{item.get_FOO_display}}

[英]Django template {{ item.get_FOO_display }} using only jinja2 without django

I use Django. 我使用Django。 I also use standalone Jinja2 to build email body from django models. 我还使用独立的Jinja2从Django模型构建电子邮件正文。

I have model with choice field and I would like to get its display value from the model instance. 我有带选择字段的模型,我想从模型实例中获取其显示值。

In django template, it is easy, for example: 在Django模板中,这很容易,例如:

{{ form.get_foo_display }}.

However, it does not work if is it outside of the django template. 但是,如果它在django模板之外,则不起作用。 My code using jinja2 is: 我使用jinja2的代码是:

Trip participation:\t{{ item.get_event_trip_display }}

where item is model instance and event_trip is choice field (the {{ item.event_trip }} works ok) 其中item是模型实例, event_trip是选择字段( {{ item.event_trip }}正常工作)

However the get_event_trip_display is rendered as: 但是, get_event_trip_display呈现为:

Trip participation: <bound method curry.<locals>._curried of <Registration: John Doe>>

Known solutions: 已知解决方案:

  1. Use {% if ... %} block to manually select the choice. 使用{% if ... %}块手动选择选项。

  2. Append the instance with new attributes in Python code: 在Python代码中为实例添加新属性:

    item.trip_parictipation_display = item.get_trip_participation_display() item.trip_parictipation_display = item.get_trip_participation_display()

My question: 我的问题:

Is there simpler way hot to call the function directly in jinja2? 有没有更简单的方法可以直接在jinja2中调用该函数? (I have a lot of fields like that) (我有很多这样的领域)

get_event_trip_display is a method. get_event_trip_display是一种方法。 Django templates automatically call methods, but Jinja2 templates don't. Django模板会自动调用方法,但Jinja2模板不会。 You need to call it explicitly: 您需要显式调用它:

{{ item.get_event_trip_display() }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM