So you use Pelican static site generator and you want to add a custom Jinja filter for use in your templates? Great!

In this post I show how to take a simple Python function and make it accessable as a custom filter. As an example we will create a filter called LinkPeek which will allow us to easily embed website screenshots into our pages.

First, we need to choose a function to become the filter, in this case we will download which has a function called api_v1:

from hashlib import md5
from urllib import quote

# signup for an APIKEY here:

def api_v1( uri, apikey=APIKEY, secret=SECRET, size='336' ):
    """ API v1 helper function"""
    token = md5( secret + uri + size ).hexdigest()
    uri = quote( uri )
    return "" % (
    uri, apikey, token, size)

Next, we hook or register this function to Pelican as a Jinja filter. We do this in the file, and it looks like this:

import sys

import liblinkpeek
JINJA_FILTERS = {'linkpeek':liblinkpeek.api_v1}

Last, we use the new filter in our template, for example:

<img src="{{|linkpeek(size='500')}}" />

In this example we create an img tag and set the src to the return value from our linkpeek filter. We pass two arguments, (the target URI) and size (the size of the image). The end result is a pixel perfect screenshot image of embeded into our page which will automatically stay fresh and up-to-date.

You might have noticed that the first argument (the target uri) is piped into the filter and then subsequint arguments are supplied like normal. This Jinja oddity also caught me off guard from conventional Python programming.

Browse the blog archives or subscribe to the full-text feed

Let us capture, store, and update webpage screenshots for you.

See Plans and Pricing
No Risks, Pay-as-you-go