Skip to content

TemplateConfig

TemplateConfig is a simple set of configurations that when passed enables the template engine.

Info

Currently Esmerald supports Jinja2 and Mako.

It is important to understand that you don't need to use the provided JinjaTemplateEngine or MakoTemplateEngine from Esmerald within the TemplateConfig.

You are free to build your own and pass it to the TemplateConfig. This way you can design however you see fit.

Requirements

This section requires jinja or mako to be installed. You can do it so by running:

$ pip install esmerald[templates]

TemplateConfig and application

To use the TemplateConfig in an application instance.

from pathlib import Path

from esmerald import Esmerald
from esmerald.config.template import TemplateConfig
from esmerald.template.jinja import JinjaTemplateEngine

template_config = TemplateConfig(
    directory=Path("templates"),
    engine=JinjaTemplateEngine,
)

app = Esmerald(template_config=template_config)

Another example

from pathlib import Path

from esmerald import Esmerald
from esmerald.config.template import TemplateConfig
from esmerald.template.mako import MakoTemplateEngine

template_config = TemplateConfig(
    directory=Path("templates"),
    engine=MakoTemplateEngine,
)

app = Esmerald(template_config=template_config)

Parameters

All the parameters and defaults are available in the TempalteConfig Reference.

TemplateConfig and application settings

The TemplateConfig can be done directly via application instantiation but also via settings.

from pathlib import Path

from esmerald import EsmeraldAPISettings
from esmerald.config.template import TemplateConfig
from esmerald.template.jinja import JinjaTemplateEngine


class CustomSettings(EsmeraldAPISettings):
    @property
    def template_config(self) -> TemplateConfig:
        """
        Initial Default configuration for the StaticFilesConfig.
        This can be overwritten in another setting or simply override
        `template_config` or then override the `def template_config()`
        property to change the behavior of the whole template_config.

        Esmerald can also support other engines like mako, Diazo,
        Cheetah. Currently natively only supports jinja2 and mako as they
        are standards in the market.
        """
        return TemplateConfig(
            directory=Path("templates"),
            engine=JinjaTemplateEngine,
        )

This will make sure you keep the settings clean, separated and without a bloated Esmerald instance.

url_for

Esmerald automatically provides the url_for when using the jinja template system, that means you can do something like this:

<link href="{{ url_for('static', path='/css/app.min.css') }}" rel="stylesheet" />