In web development, to design and insert data into HTML page, we need to use a template engine. Unfortunately, there is no template engine in Sanic web framework, we have to install our own template engine to be able to create HTML page with necessary data. 

 

To date, among template engines for Python web frameworks, Jinja2 is very popular and is being used as the default template engine by a number of well-known Python web framework such as Flask, Django, Babel, and Pylons. To use Jinja2 template engine in our Sanic project, we must install it by writing the command as below:

 

pip install Jinja2

 

First of all, Jinja2 package requires us to create a folder in the root project under the name “templates” and import three callable objects to buildup an environment suitable for looking for HTML page in the “templates” folder.

 

#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):
    return html('Welcome to Khmer Web Sanic!')

 

The reason we store template environment in Sanic application object because we want to use this template environment to render other HTML pages in other modules by usin get_app( ) method to get Sanic application object. Doing so, we will not need to import template object and create template environment all over again. 

 

To render any HTML page, we just pull that page from the templates folder and call render method on template object by passing as much data as we could to the HTML page.

 

#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):
    template = app.ctx.template.get_template("base.html")
    return html(template.render())

 

<!--templates/base.html-->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Sanic web framework</title>
  </head>
  <body>
    <p>Welcome to Khmer Web Sanic!</p>
  </body>
</html>