Templating.
Batman wanted to quickly render html pages on the website. He wanted to use a templating engine to render the html pages. Robyn told him that he can use the Jinja2 templating engine to render the html pages. He can use the JinjaTemplate class to render the html pages.
Batman was excited to learn that he could add events as functions as well as decorators.
Request
from robyn.templating import JinjaTemplate
current_file_path = pathlib.Path(__file__).parent.resolve()
JINJA_TEMPLATE = JinjaTemplate(os.path.join(current_file_path, "templates"))
@app.get("/template_render")
def template_render():
context = {"framework": "Robyn", "templating_engine": "Jinja2"}
template = JINJA_TEMPLATE.render_template(template_name="test.html", **context)
return template
test.html file
Request
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Results</title>
</head>
<body>
Hello {{ framework }}! You're using {{ templating_engine }}.
</body>
A quick render shortcut
Batman didn't always want to construct a JinjaTemplate by hand. Robyn told him that for the common case — a templates folder next to his application file — he can use the render shortcut instead.
render resolves the templates directory relative to the file that calls it, so there is no need to wire up paths with pathlib. It renders with Jinja2 by default; pass a different templates_dir to point at another folder, or a custom TemplateInterface via template_engine to use a different templating engine.
Request
from robyn.templating import render
@app.get("/template_render")
def template_render():
# Jinja2 is the default templating engine
return render("index.html", name="Batman")
Supporting Custom Templating Engines
Batman was also super excited to know that Robyn allows the support of custom templating engines.
To do that, you need to import the TemplateInterface from robyn.templating
Request
from robyn.templating import TemplateInterface
Then You need to have a render_template method inside your implementation. So, an example would look like the following:
Request
class JinjaTemplate(TemplateInterface):
def __init__(self, directory, encoding="utf-8", followlinks=False):
self.env = Environment(
loader=FileSystemLoader(
searchpath=directory, encoding=encoding, followlinks=followlinks
)
)
def render_template(self, template_name: str, **kwargs):
return self.env.get_template(template_name).render(**kwargs)
What's next?
Now, Batman wanted to have the ability to redirect the endpoints.
