askama
askama copied to clipboard
Support for stateful filters
Right now askama uses a module as the source of filter functions. This works well in general, but has issues if the filter requires some state. In that case you'd need to setup a static variable, worry about threading issues, etc. Here's an example from some in-progress code
It would be nice if there was an option to use a field of the Template
struct as the source for filters. Then you could construct your filters type however you wanted and use that. I'm thinking some system like:
- The feature is enabled with an annotation like:
#[template(filters = "field")]
- Then in the generated code, a filter call gets translated into a call to the filters field (
foo|bar
->self.filters.bar(foo)
)
Why not just call a method on the context type instead?
That would work, it just feels like too much typing if you're using the filters often in your templates.
I feel like this is pretty niche - it feels reasonable to me that filters are stateless - and I don't find the proposed configuration API very compelling. Seems likely that making method calls in way that's not very verbose (maybe through an Askama macro?) is feasible.
Fair enough. I'm not sure how the macro would work, but another option would be something like jinja's contextfilter
decorator, so that the filter function would get the context is its first argument. I'm just not sure how the configuration would work.