Jinja2 is a text-based template engine. You can use it to create HTML, XML or other markup formats that are returned to the user via an HTTP request.

Example

from jinja2 import Template

t = Template("Current login user is {{ name }}")
t.render(name="Iron Man")

Current login user is Iron Man.

Read More

app.yaml

Add Jinja2 as a required libary.

runtime: python27
api_version: 1
threadsafe: yes

libraries:
- name: jinja2
  version: latest

handlers:
- url: /favicon\.ico
  static_files: static/images/favicon.ico
  upload: static/images/favicon\.ico

- url: /.*
  script: main.app

templates

Create a new templates folder to store all template files. The app folder will have below structure

app/
    __init__.py/
    handlers/
        __init__.py/
        base.py/
        bot.py/
    models/
        __init__.py/
        chat.py/
    templates/
    	base.html

base.html

Under templates folder, create a new file ‘base.html’. It

<!DOCTYPE html>
<html lang="en">
<head>
    <title>{{ title }}</title>
</head>
<body>
    <ul id="navigation">
        <li><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
    </ul>
    <h2>{{ myContent }}</h2>
</body>
</html>

base.py

  • Imports jinja2 and creates a jinja2.Environment object.
  • Refactor handler method to render using jinja2
import webapp2
import jinja2
import os

# our template files are stored under templates folder.
# we need to create a directory point to templates folder.
template_dir = os.path.join(os.path.dirname(__file__), '../templates')

# create jinja2.Environment with the above directory.
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir),
                               extensions=['jinja2.ext.autoescape'],
                               autoescape=False,
                               trim_blocks=True)


class Handler(webapp2.RequestHandler):
    def render_template(self, template_name, **kwargs):
            if not kwargs:
                kwargs = {}
            t = jinja_env.get_template(template_name)
            self.response.write(t.render(kwargs))


class MainPage(Handler):
    def get(self):
        kwargs = {
            'title': 'Home',
            'myContent': 'Hello, This\' Telegram Bot website!'
        }
        self.render_template('base.html', **kwargs)


class AboutPage(Handler):
    def get(self):
        kwargs = {
            'title': 'About',
            'myContent': 'I\'m Telegram Bot'
        }
        self.render_template('base.html', **kwargs)

Result

Home Page