Template Providers#

This page documents the machinery behind template providers, the middleware that process the template files and inject template variables into them.

class prept.TemplateProvider(settings: dict[str, Any])#

Base class for all template providers.

Template providers are “middleware” classes that process the content of template files at generation time and inject the values of template variables.

All template providers, external or provided by Prept, inherit from this class and implement the process_content() and process_path() methods.

Prept provides the following built-in template providers:

settings#

Dictionary containing settings for provider from preptconfig.json.

Added in version 0.4.0.

process_path(path: pathlib.Path, context: GenerationContext) pathlib.Path#

“Processes the given path and replaces the.

This returns the pathlib.Path object representing the processed path.

Parameters:
  • path (pathlib.Path) – The path to process.

  • context (GenerationContext) – The generation context containing generation time information.

process_content(file: BoilerplateFile, context: GenerationContext) str | bytes#

Processes the file content and inject variables into it.

This returns the processed file content generated from template in textual (string) or binary (bytes) format.

Parameters:

Built-in Providers#

Prept provides the following template providers built-in to cater common use cases. Support for more template providers will be added in future.

StringTemplateProvider#

class prept.StringTemplateProvider(settings: dict[str, Any])#

$-substitutions based templates by string.Template.

This uses string.Template.safe_substitute() to ensure that any invalid or missing variables are silently ignored at generation time.

This can be used by setting template_provider to stringsub

Jinja2TemplateProvider#

class prept.Jinja2TemplateProvider(settings: dict[str, Any])#

Provider based on Jinja2 templates.

This template provider requires Jinja2 to be installed.

Jinja templates are commonly used for HTML files in web frameworks such as Flask. However, it can be used for any kind of source file.

The following is an example of Jinja template HTML file (taken directly from Jinja2 documentation):

<!DOCTYPE html>
<html lang="en">
<head>
    <title>My Webpage</title>
</head>
<body>
    <ul id="navigation">
    {% for item in navigation %}
        <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
    {% endfor %}
    </ul>

    <h1>My Webpage</h1>
    {{ a_variable }}

    {# a comment #}
</body>
</html>

For more information, please refer to Jinja documentation: https://jinja.palletsprojects.com/

This can be used by setting template_provider to jinja2