Keats / tera

A template engine for Rust based on Jinja2/Django
http://keats.github.io/tera/
MIT License
3.58k stars 291 forks source link

Allow functions/filters to access their constant arguments at compile time #940

Open clarfonthey opened 1 month ago

clarfonthey commented 1 month ago

Basically following up this discussion: https://github.com/getzola/zola/pull/2581#discussion_r1806706366

Right now, functions and filters don't have special access to constant arguments, which means that, for example, regex filters will have to compile their expression every time they run. There are ways around this, but what feels reasonable is determining what arguments are constant and then passing those during compilation to affect the final result.

Another option could just be to have a lazy cell in the function state that stores a compiled Regex and just replaces it if the pattern changes, but it feels like being able to optimize the functions further could help performance for large cases. Effectively, we could pre-evaluate large chains of logic if we do this right.

Keats commented 1 month ago

Easiest way (I think) would be to define a struct for the filters/tests using regex and store the compiled versions in a hashmap in that struct. I don't know if people are using those filters/tests with dynamic patterns though?

clarfonthey commented 1 month ago

That's mostly why I proposed using a static cell instead of a hashmap: if they do end up doing it dynamically, it'll recompile every time, but in the common case where it's constant, they won't.