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.
py
# GET /hello_world
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 templatepy
# GET /hello_world
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 templatetest.html 文件
html
<!-- GET /hello_world -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Results</title>
</head>
<body>
Hello {{ framework }}! You're using {{ templating_engine }}.
</body>
</html>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
py
# GET /hello_world
from robyn.templating import TemplateInterfacepy
# GET /hello_world
from robyn.templating import TemplateInterfaceThen You need to have a render_template method inside your implementation. So, an example would look like the following:
py
# GET /hello_world
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, **kwargs):
return self.env.get_template(template_name).render(**kwargs)py
# GET /hello_world
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.