Search code examples
jinja2mkdocs

Add custom Jinja2 filters/tests to MkDocs


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.


Solution

  • 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