Template engine uses a kind of programming language for the design of HTML structure and to insert data into it. However, this language is a lightweight programming language, and we do not need to spend months to learn the language.
At this point, we will think to the beauty of Bottle.py web framework, because it uses Python language for its template engine. Many web developers always raise a question why we need to learn new language for template engine, not the same language that we currently use. Using the same language allows us to move really fast in designing HTML page, it also helps to increase the production in web development. Moreover, there are a lot of things in Bottle.py that make people love this framework.
In fact, Jinja2 template language is composed of variable and statements such if and for loop, but this language is heavily inspired by Python programming language. As the result, if you already know Python, you will pickup Jinja2 template language very fast.
To start, variable in Jinja2 language comes from Python variable that we pass to render( ) method of the template object.
#routes/front/index.py
from sanic import Sanic
from sanic.response import html
from jinja2 import Environment,PackageLoader,select_autoescape
app = Sanic.get_app('Khmerweb')
app.static("/static", "static")
app.ctx.template = Environment(loader=PackageLoader("index"),autoescape=select_autoescape())
@app.route("/")
async def home(req):
kdict = {}
kdict['siteTitle'] = 'Khmer Web'
kdict['pageTitle'] = 'Home Page'
template = app.ctx.template.get_template("base.html")
return html(template.render(data=kdict))
<!--templates/base.html-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>{{data['siteTitle']}} | {{data['pageTitle']}}</title>
</head>
<body>
<p>Welcome to Khmer Web Sanic!</p>
</body>
</html>
To insert data into HTML page, we use {{ }} sign to include the value of the variable sent by the handler through render( ) method in template object. Most of the time, the variable sent to render( ) method is a regular Python dictionary object for which we have to use Python dictionary key to get the value.