4ch1m / intellij-quick-jinja

A plugin for the IntelliJ platform to quickly render and review Jinja templates.
MIT License
2 stars 1 forks source link

Support custom filters. #2

Open Ayfri opened 3 months ago

Ayfri commented 3 months ago

Hey, now the plugin correctly works on Windows, but doesn't with custom filters. I don't really know how you would do this, maybe just write down some place holders values as custom filters can be defined in many ways.

For example, here's how I do it personally:

def format_big_number(value: int, use_symbol: bool = False, use_comma: bool = False) -> str:
    formatted_value = f'{value:,}'.replace(',', ' ')

    if use_symbol:
        if value >= 1_000_000_000:
            formatted_value = f'{value / 1_000_000_000:.1f} Md'
        if value >= 1_000_000:
            formatted_value = f'{value / 1_000_000:.1f} M'
        if value >= 1_000:
            formatted_value = f'{value / 1_000:.1f} k'
        formatted_value = str(formatted_value)
    return formatted_value.replace('.', ',') if use_comma else formatted_value

def filter_by_key_value(items: list[object], path: str, value: any) -> list[object]:
    keys = path.split('.')
    return [item for item in items if reduce(getattr, keys, item) == value]

def regex_match(value: str, pattern: str) -> bool:
    return re.search(pattern, value) is not None

def regex_replace(s: str, find: str, replace: str) -> str:
    return re.sub(find, replace, s)

def init_filters(app: Flask) -> None:
    app.jinja_env.filters['format_number'] = format_big_number
    app.jinja_env.filters['filter_by'] = filter_by_key_value
    app.jinja_env.filters['regex_match'] = regex_match
    app.jinja_env.filters['regex_replace'] = regex_replace
    ...many more filters

# run_flask.py

def create_app() -> Flask:
    app = Flask(__name__, static_folder='flaskr/static', template_folder='flaskr/templates')
    app.config.from_prefixed_env()
    ...many other settings and configurations

    init_filters(app)

if __name__ == '__main__':
    app = create_app()
    app.run()
4ch1m commented 3 months ago

Hey there,

thanks for your feedback.

I understand that this is a pretty common use-case for Jinja-templating.

However, I also think that something like that might be out of scope for this plugin.

It basically aims to quickly test "stock" Jinja templates (with the addition of widely used Ansible-specific filters).

(The plugin will never be able to replace a "proper" Jinja run with all imports, custom filters, etc. The possibilities there are endless.)

I'm also not sure where/how this should be configured by the user, if such a feature would be integrated into the plugin. :thinking:

I guess I'll have to sleep on it in a few nights. :smile:

Ayfri commented 3 months ago

I see, thanks for the reply nonetheless !