LarryDpk
发布于 2023-07-05 / 134 阅读
0

Python Template Engine Jinja2 and Integrate with Flask

Python Template Engine Jinja2 and Integrate with Flask

Jinja Example

Jinja is quite easy to use. Let me give an example to render markdown file.

Template file hello.md.jinja2:

# Hello, {{name}}
Welcome to {{website}}

# The skills
{% for i in skills %}{{i}} {% endfor %}

In python code, just read the template and render with the parameters:

from jinja2 import Template
import pathlib


def render(name, website):
    current_path = pathlib.Path(__file__).parent.parent.resolve().__str__()
    print(current_path)

    file = open(current_path + '/templates/hello.md.jinja2', 'r')
    content = file.read()
    file.close()
    template = Template(content)
    rendered_md = template.render(name=name, website=website, skills=['Java', 'Python', 'Docker', 'Kubernetes'])
    print(rendered_md)

    output = open(current_path + '/output/hello.' + website + '.md', 'w')
    output.write(rendered_md)
    output.close()
    return rendered_md


if __name__ == '__main__':
    render('Larry', 'www.pkslow.com')
    render('Deng', 'www.google.com')

Create Template with template content:

template = Template(content)

Render with parameters:

rendered_md = template.render(name=name, website=website, skills=['Java', 'Python', 'Docker', 'Kubernetes'])

The result:

# Hello, Larry
Welcome to www.pkslow.com

# The skills
Java Python Docker Kubernetes 

All the code can check on pkslow-samples/python/jinja-example

Integration with Flask

Flask is a lightweight WSGI framework, we can use Flask to build web application.

Python code to render the HTML content and return:

from flask import Flask, render_template

app = Flask(__name__)


@app.route("/")
def home():
    return render_template("index.html", title='main page')


@app.route("/list")
def default():
    return render_template("list.html", title='Skill List',
                           skills=['Java', 'Python', 'Docker', 'Kubernetes', "Google Cloud Platform"])


if __name__ == "__main__":
    app.run(debug=False)

Template file index.html:

{% extends "layout.html" %}
{% block content %}
<ul>
    <li><a href="/list"> list </a></li>
</ul>
{% endblock %}

Template file list.html:

{% extends "layout.html" %}
{% block content %}
<h2>The skill list</h2>
<ul>
    {% for skill in skills%}
    <li>{{skill}}</li>
    {% endfor %}
</ul>
{% endblock %}

The result for /:

The result for /list:

All the code can check on pkslow-samples/python/jinja-with-flask


References: