Skip to content

Custom Filter for Jinja Renderer #9

@suhendiandigo

Description

@suhendiandigo

Hello @radeklat , thanks for the last update to expose classes. So far, I am enjoying my experience in auto generating configurations for my apps :D.

Currently I am contemplating the solution for one of my use cases. I want to display the class title and render each classes sorted by their titles. I displayed the title by using the following macro:

{% macro class_title(class) -%}
{% if class.Config|attr('title') -%}
{{ class.Config.title }}
{%- else -%}
{{ class.__name__ }}
{%- endif %}
{%- endmacro %}

However, I reached a conundrum while trying to sort the classes by their title. After some tinkering, I figured out a way to achieve this is to add custom filters. So I modified the main.py (for testing purpose):

class_title = env.globals["class_title"] = lambda x: x.Config.title if hasattr(getattr(x, 'Config', None), 'title') else x.__name__
env.filters["sort_title"] = lambda x: list(sorted(x, key=class_title))

And I use them in the following way:

{% for class in classes|sort_title %}
{{ heading(2) }} {{ class_title(class) }}
{% endfor %}

I am wondering what are your thoughts on this and if it is worth supporting custom filters without having to modify the main.py. I will gladly write a pull request if you think that this is a good idea/feature to support.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions