mozilla / nunjucks

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)

Home Page:https://mozilla.github.io/nunjucks/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Template loader with contextual info

dcarniel opened this issue · comments

Hello,

I'm using nunjucks with a set of templates which have "variants" for multiple channels (email, HTML page, PDF...), the idea being to render the same "content" with templates that adapt the content to the channel.

I've implemented this by storing templates in a database with the different "variants" and manually building the inheritance. It works fine but forces me to provide a custom UI to edit templates.

I would like to use files so templates can be edited through a generic text editor (like VS Code) and stored on a Filesystem. I though I could use a naming convention such as ..njk but I don't think I can write my own loader to handle this for mainly two reasons:

  1. I don't have any "contextual" information when executing the loader to figure out the requested "channel"
  2. I think I might face issues with the caching since the templates would be called by their name but the actual file loaded depend on the channel (which might change between requests).

Could it be possible to at least have extra (dynamic) information besides the template name available in the loader ? Ideally this should be used as key for the cache too, but at minimum I could try disabling cache.

Any idea / comparable experience is welcome :)

You can write loader with channel as option (you should have different nunjucks environments for each channel)

Writing loader is not really hard https://mozilla.github.io/nunjucks/api.html#loader

My initial idea was to write an "intelligent" loader which could serve all channels, the channel being a kind of "parameter" of the rendering.

That said I'll look into the option you describe (create environments per channel with a parameterised loader), that could work and handle the fact that only some templates are overloaded and have cache working in that case.

I'll update this ticket for reference when I'm done implementing that.

Can you add some examples of how your architecture looks like?