Search code examples
jinja2pelican

Current year, 'now' is undefined in Pelican template


I'm trying to display the current year in my footer in Pelican website. My understanding is that Pelican uses Jinja2 template.

In my footer.html I use:

<span>{{ now().year }}</span>

And I use it in my base.html as

{% include 'footer.html' %}

But when I generate the page I've got the error

Undefined Error: 'now' is undefined

And I cannot find the reason.

Is there any trick/setting/plugin I need to use this?


Solution

  • Pelican provides a strftime extra filter to Jinja, that works exactly like Python's strftime.

    Here are the sources of this finding:

    1. this line from their code base
    2. and this page of documentation

    This said, you will need a datetime object to use this filter on.

    The later can be obtained by modifying your configuration file, pelicanconf.py, adding those two lines

    from datetime import datetime
    NOW = datetime.now()
    
    ## Mind that:
    ##   All the setting identifiers must be set in all-caps, 
    ##   otherwise they will not be processed.
    ## @see https://docs.getpelican.com/en/latest/settings.html#settings
    

    Now, in your template, you can start using this newly created NOW variable and apply the strftime format, which means that you want %Y for the year:

    {{ NOW | strftime('%Y') }}