Using Pelican's article.summary

Posted on in Programming

cover image for article

I'm using Jinja2 templates with my new Pelican-based articles. If you have Django experience, you'll feel right at home using Jinja2 templates. I decided early on that I wanted to create my own theme from scratch and keep it as basic as possible. (In fact, 'basic' is the name of my theme.) One of the early things I've struggled with is how to handle certain <meta> tags. The 'description' tag has been especially interesting.

My first attempt was to set the description using metadata in my markdown file.
That looked something like this:

{% if article.description %}
    <meta name="description" content="{{ article.description }}" />
{% endif %}

That solution works fine, but requires me to set a description in the metadata
of every article. I'm lazy, so an easier solution would be preferable. The
answer to that is Pelican's summary feature (invoked via article.summary).
The length of the summary is controlled by the SUMMARY_MAX_LENGTH setting and
defaults to 50 words. Here's how the code changed once I decided to use
article.summary.

{% if article.description %}
    <meta name="description" content="{{ article.description }}" />
{% else %}
    <meta name="description" content="{{ article.summary|striptags }}" />
{% endif %}

The important bit here is to pass article.summary through the striptags
filter. That will ensure that any HTML tags you might have included will get
removed. If those appear inside your meta tag content, it will wreak havoc
on how your site displays.

Slaptijack's Koding Kraken