2

While writing a Jinja2 template for MkDocs, I need some processing that is not covered by the filters/tests available (specifically, I need date formatting, which is a recurring example for custom filters in Jinja2-related resources across the Web). How can I define my own filters/tests and use them from templates?

To clarify the question, I know how to register new filters/tests in a Jinja2 environment from Python. My issue is that, as a user of MkDocs, I do not configure Jinja2 myself. So what I’m looking for is a way to hook into the setup that MkDocs performs.

I assume it is possible to add filters from a plugin. In fact, I have found one such plugin (undocumented and apparently not under active development, unfortunately). However, I hope that there is a simpler, local solution; one that would not involve implementing a plugin, packaging it as a Python package and publishing it on PyPi.

Maëlan
  • 3,586
  • 1
  • 15
  • 35

1 Answers1

3

A possible solution is to use mkdocs-simple-hooks that allows to implement the hooks without needing to create a plugin. For example in your case:

plugins:
  - mkdocs-simple-hooks:
      hooks:
        on_env: "docs.hooks:on_env"

docs/hooks.py

def on_env(env, config, files, **kwargs): 
    env.filters['my_filter'] = my_filter
    env.tests['my_test'] = my_test
    return env
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Wonderful! Now I have access to the full power of plugins, without the trouble of packaging/publishing. I actually prefer using this plugin over `mkdocs-jinja2-filters-plugin`, since it is more general and more flexible (I also need plugin powers for other things). – Maëlan Apr 28 '21 at 17:26
  • @Maëlan If you can improve my post feel free to do so, I am not an expert in mkdocs so I only gave a trivial example and without testing it – eyllanesc Apr 28 '21 at 17:36
  • Thanks for the edition, sorry for the trouble. :-) – Maëlan Apr 28 '21 at 17:44