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 liblinkpeek.py which has a function called api_v1:

#!/usr/bin/python
from hashlib import md5
from urllib import quote

# signup for an APIKEY here: https://linkpeek.com/signup
APIKEY = ''
SECRET = ''

def api_v1( uri, apikey=APIKEY, secret=SECRET, size='336' ):
    """LinkPeek.com API v1 helper function"""
    token = md5( secret + uri + size ).hexdigest()
    uri = quote( uri )
    return "https://linkpeek.com/api/v1?uri=%s&apikey=%s&token=%s&size=%s" % (
    uri, apikey, token, size)

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

import sys
sys.path.append('.')

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

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

<img src="{{russell.ballestrini.net|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, russell.ballestrini.net (the target URI) and size (the size of the image). The end result is a pixel perfect screenshot image of russell.ballestrini.net 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