Static Site Generator

How-to: How to add dynamic data to a page with a plugin?

How to add dynamic data to a page with a plugin?

Step 1

Add a new plugin file in the plugins directory. A plugin is a Python script.

plugins
+--- data.py

Step 2

We want to add a new dynamic variable. The event is page_data_merged. This event is used after merging layouts and page data.

In this example, we add the current year to be added in the copyright.

from datetime import datetime


def page_data_merged(data: dict, args: dict) -> dict:
    data['year'] = datetime.now().year
    return data

In the footer block template, we now add the variable:

<p>Copyright @ {{ year }} Company</p>

Arguments

In the args argument, we find the current page path:

def page_data_merged(data: dict, args: dict) -> dict:
    data['welcome'] = ''
    if args['path'] == '/index.html':
        data['welcome'] = 'Welcome to the homepage!'
    return data

The data argument contains the merged json data for the page:

def page_data_merged(data: dict, args: dict) -> dict:
    prefix = 'Stapy - '
    if 'meta_title' in data and prefix not in data['meta_title']:
        data['meta_title'] = prefix + data['meta_title']
    return data

Debug

To visualize final page data, add the _page key before the page path in the URL:

http://127.0.0.1:1985/_page/index.html

Next