askama icon indicating copy to clipboard operation
askama copied to clipboard

Support for stateful filters

Open bendk opened this issue 3 years ago • 4 comments

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))

bendk avatar Dec 09 '21 15:12 bendk

Why not just call a method on the context type instead?

djc avatar Dec 09 '21 15:12 djc

That would work, it just feels like too much typing if you're using the filters often in your templates.

bendk avatar Dec 09 '21 15:12 bendk

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.

djc avatar Dec 09 '21 15:12 djc

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.

bendk avatar Dec 09 '21 15:12 bendk