You can register a custom Jinja filter that tells Jinja to use the Enum value (.value
) if it receives an Enum object.
For example, you have this template.html:
<body>
{% for obj in objects %}
{{ obj }}<br>
{% endfor %}
</body>
and you pass an objects
to the template which can contain different types, like this:
@app.route('/', methods=['GET'])
def index():
objects = get_objects_from_somewhere()
# This returns different data types, maybe multiple enums
# Ex. ['somename', (22, 44, 66), Size.ONE, AnotherEnum.XYZ]
return render_template('template.html', objects=objects)
Define a Jinja filter function like this:
from enum import Enum
@app.template_filter()
def to_string(obj):
if isinstance(obj, Enum):
return obj.value
# For all other types, let Jinja use default behavior
return obj
A filter function receives the value
from the {{ value | filter_name }}
in the template, and then you need to return what Jinja will display. Read more about on custom filters here from the Jinja docs.
Then use it in your template like this:
<!doctype html>
<body>
{% for obj in objects %}
{{ obj | to_string }}<br>
{% endfor %}
</body>
In this way, you can handle different types as well as reuse the filter across different templates. It also separates the view/UI code from the route codes.