Include fragments in static site source files to be processed by Pelican

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.

Author: Omer Zak

I am deaf since birth. I played with big computers which eat punched cards and spew out printouts since age 12. Ever since they became available, I work and play with desktop size computers which eat keyboard keypresses and spew out display pixels. Among other things, I developed software which helped the deaf in Israel use the telephone network, by means of home computers equipped with modems. Several years later, I developed Hebrew localizations for some cellular phones, which helped the deaf in Israel utilize the cellular phone networks. I am interested in entrepreneurship, Science Fiction and making the world more accessible to people with disabilities.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.