I use Pelican to generate static websites using markdown files.
I found that there are text fragments that I want to reuse in several of my web pages, but not in all of them. So I needed a way to include those fragments in the markdown pages, using a suitable include directive, rather than add them to the template files used by Pelican to generate the final HTML files.
I googled for a way to use include files in markdown files to be processed by Pelican. I was led to unhelpful answers. For example, the mdx_include module. I rejected it because I found no easy way for lazy people to integrate it into Pelican.
Eventually I converged upon the following solution.
Pelican uses the Jinja2 templating engine, which has the {% include 'filename' %}
directive.
By default, Pelican subjects only template files to Jinja2 processing. So, to use the include directive in my own markdown files, I need a way to have them go through Jinja2 processing as well. This is what the jinja2content Pelican plugin does.
To install it:
pip install pelican-jinja2content
To use it, add the following to your `pelicanconf.py` file:
PLUGINS = [ . . . 'pelican.plugins.jinja2content', . . . ] # jinja2content configuration IGNORE_FILES = [ 'includes' ] JINJA2CONTENT_TEMPLATES = [ './includes', ]
Then add your include files to the ./content/includes
subdirectory. They may have any extension you want including .md
. I recommend .mdinc
to tell them apart from your article markdown files. Instead of includes
, you may use any subdirectory name by changing the configuration above.
Before doing sophisticated things with your include files, read the plugin’s documentation and understand the limitations of using Jinja2 tags inside your include and markdown files.