[Pelican] Get Single Page or Article by slug Metadata in Theme

Sometimes we want to get a single page or article by some metadata in theme. This post shows how to use a custom Jinja2 filter to get a single page or article by slug metadata in the theme.

First, add the following filter code in your pelicanconf.py:

# custom Jinja2 filter
def get_by_slug(objs, slug):
    for obj in objs:
        if obj.slug == slug:
            return obj

    "get_by_slug": get_by_slug,

Then you can use the custom filter to select the page or article you need in the theme. For example, you can use as follows in index.html:

{% set intro = (pages|get_by_slug("introduction")) %}
{% set hello = (articles|get_by_slug("hello-world")) %}

<div>Title of page: {{ intro.title }}</div>
<div>Title of article: {{ hello.title }}</div>

Tested on: Ubuntu Linux 16.10, Python 2.7.12+, Pelican 3.7.0.


[1]new arch: FIXME: URL issue · siongui/shenfang@33b9932 · GitHub