ΠŸΠ΅Ρ€Π΅ΠΉΡ‚ΠΈ ΠΊ ΡΠΎΠ΄Π΅Ρ€ΠΆΠ°Π½ΠΈΡŽ

Template class

Warning

The current page still doesn't have a translation for this language.

But you can help translating it: Contributing.

esmerald.datastructures.template.Template

Bases: ResponseContainer[TemplateResponse]

Template allows to pass the original template name and an alternative in case of exception not found.

name instance-attribute

name

The template name in the format of a path.

Example: templates/base/index.html

context class-attribute instance-attribute

context = {}

Any context that should be sent to the templates to be rendered.

Example

from esmerald import Esmerald, Gateway, Template, get
from esmerald.datastructures import Cookie, ResponseHeader


@get(
    path="/home",
    response_headers={"local-header": ResponseHeader(value="my-header")},
    response_cookies=[
        Cookie(key="redirect-cookie", value="redirect-cookie"),
        Cookie(key="general-cookie", value="general-cookie"),
    ],
)
def home() -> Template:
    return Template(
        name="my-tem",
        context={"user": "me"},
        alternative_template=...,
    )

alternative_template class-attribute instance-attribute

alternative_template = None

An alternative template name if the name is not found. This should also be in the format of a path.

Example: templates/base/alternative_index.html

to_response

to_response(headers, media_type, status_code, app)
PARAMETER DESCRIPTION
headers

TYPE: Dict[str, Any]

media_type

TYPE: Union[MediaType, str]

status_code

TYPE: int

app

TYPE: Type[Esmerald]

Source code in esmerald/datastructures/template.py
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def to_response(
    self,
    headers: Dict[str, Any],
    media_type: Union["MediaType", str],
    status_code: int,
    app: Type["Esmerald"],
) -> "TemplateResponse":
    from esmerald.exceptions import ImproperlyConfigured
    from esmerald.responses import TemplateResponse

    if not app.template_engine:
        raise ImproperlyConfigured("Template engine is not configured")

    data: Dict[str, Any] = {
        "background": self.background,
        "context": self.context,
        "headers": headers,
        "status_code": status_code,
        "template_engine": app.template_engine,
        "media_type": media_type,
    }
    try:
        return TemplateResponse(template_name=self.name, **data)
    except TemplateNotFound as e:  # pragma: no cover
        if self.alternative_template:
            try:
                return TemplateResponse(template_name=self.alternative_template, **data)
            except TemplateNotFound as ex:  # pragma: no cover
                raise ex
        raise e