How do macros and Jinj2 templates fit together? How to approach and advanced project #197
fralau
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I wanted to share my approach to more advanced projects (this is copied from #195, this part).
Please free to give your feedback, examples, own experience, etc.
The tools in the toolbox
When you work with different tools at the same time, the first step to get a crystal clear picture of what each tool is for (with its strengths and weaknesses) and what essential role it is playing in the ecosystem. So its important to differentiate them, roughly:
How Mkdocs-Macros expands the toolbox
Mkdocs-Macros expand this toolbox by adding the power of jinja2 templates.
So here would be the guiding principles, if want to you wish to extract maximum power from Mkdocs-Macros:
extra
section in your config file).Do not hesitate to make liberal use the following jinja2 constructs:
for
)if
)a. jinja2 syntax
b. Pure Python (as a module)
jinja2 versus Python macros?
TLDR: write your macros in Python.
The long answer: Which you chose is, really, whichever you prefer, since they do the same. However, here is my viewpoint about it, i.e. the philosophy behind Mkdocs-Macros.
I suppose that the designers of Jinja2 added the possibility of defining jinja2 macros inside templates as a convenience solution, an extra flexibility; that's because writing a Python function (loaded when booting the jinja2 environment) would imply a change to the project's "hard-code"; and depending on how the code or project is organized, it can be too much work. The syntax of jinja2 macros works and is actually quite elegant, so it could be a time saver. But let's be honest: compared to Python, that syntax is fussy.
But with Mkdocs-Macros, the operating principle has been turned on its head, with a little white magic in the plugin (dynamic loading of Python code). A key aim of the project was to make it super-easy to write a Python module to define macros (and filters) specifically for a website. This was born out of my frustration with wikis like Confluence, which turned writing macros into an adventure into Javassic Park, complete with skeletons and Velocity raptors.
I just wanted to express: "here is my function" with a
def
in Python, put a decorator on it that defines whether it's a macro or a filter, and that had to be that.Allowing a programmer to quickly write macros in Python on a "per-website" basis, was the whole point of this plugin.
More on it on the About page of the project.
Beta Was this translation helpful? Give feedback.
All reactions