Zum Inhalt

Templating - Jinja2Templates

You can use the Jinja2Templates class to render Jinja templates.

Read more about it in the FastAPI docs for Templates.

You can import it directly from fastapi.templating:

from fastapi.templating import Jinja2Templates

fastapi.templating.Jinja2Templates

Jinja2Templates(
    directory, context_processors=None, **env_options
)

templates = Jinja2Templates("templates")

return templates.TemplateResponse("index.html", {"request": request})

PARAMETER DESCRIPTION
directory

TYPE: Union[str, PathLike]

context_processors

TYPE: Optional[List[Callable[[Request], Dict[str, Any]]]] DEFAULT: None

**env_options

TYPE: Any DEFAULT: {}

Source code in starlette/templating.py
65
66
67
68
69
70
71
72
73
74
75
def __init__(
    self,
    directory: typing.Union[str, PathLike],
    context_processors: typing.Optional[
        typing.List[typing.Callable[[Request], typing.Dict[str, typing.Any]]]
    ] = None,
    **env_options: typing.Any,
) -> None:
    assert jinja2 is not None, "jinja2 must be installed to use Jinja2Templates"
    self.env = self._create_env(directory, **env_options)
    self.context_processors = context_processors or []

env instance-attribute

env = _create_env(directory, **env_options)

context_processors instance-attribute

context_processors = context_processors or []

get_template

get_template(name)
PARAMETER DESCRIPTION
name

TYPE: str

Source code in starlette/templating.py
93
94
def get_template(self, name: str) -> "jinja2.Template":
    return self.env.get_template(name)

TemplateResponse

TemplateResponse(
    name,
    context,
    status_code=200,
    headers=None,
    media_type=None,
    background=None,
)
PARAMETER DESCRIPTION
name

TYPE: str

context

TYPE: dict

status_code

TYPE: int DEFAULT: 200

headers

TYPE: Optional[Mapping[str, str]] DEFAULT: None

media_type

TYPE: Optional[str] DEFAULT: None

background

TYPE: Optional[BackgroundTask] DEFAULT: None

Source code in starlette/templating.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def TemplateResponse(
    self,
    name: str,
    context: dict,
    status_code: int = 200,
    headers: typing.Optional[typing.Mapping[str, str]] = None,
    media_type: typing.Optional[str] = None,
    background: typing.Optional[BackgroundTask] = None,
) -> _TemplateResponse:
    if "request" not in context:
        raise ValueError('context must include a "request" key')

    request = typing.cast(Request, context["request"])
    for context_processor in self.context_processors:
        context.update(context_processor(request))

    template = self.get_template(name)
    return _TemplateResponse(
        template,
        context,
        status_code=status_code,
        headers=headers,
        media_type=media_type,
        background=background,
    )