Flask Station Notes - Using jinjia Template

Keywords: JQuery JSP Java Python

The jinjia syntax is similar to jsp in Java Web. It can interact directly with the background in html with specific grammar rules and implement some simple logical operations.

  1. Background function
@blog.route("/blog")
def blog():
    data = [...]
    return render_templates("index.html", data=data)
  1. Variable representation
{{ data[0] }}
  1. if judgement
{% if data %}
<p>{{ one }}<p>
{% endif %}
  1. for cycle
{% for one in data %}
<p>{{ one }}<p>
{% endfor %}
  1. Block block

Using block blocks, we can define a template html to achieve the unification of page style.

base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>{% block title %}Title{% endblock %}</title>
</head>
<body style="background-color:#eeeeee">
    <!--Page header-->
    <div id="divHead" class="row" style="background-color: #4d91a1">
    </div>

    <!--Content block-->
    {% block content %}
    {% endblock %}

    <!--Page tail-->
    <div class="row" style="background-color: #333333; width: 100%; height: 40px; position: fixed; bottom: 0px"></div>
    <script src="/static/plugin/jquery/jquery-1.9.1.min.js"></script>
    <script src="/static/plugin/bootstrap-3.3.7/js/bootstrap.min.js"></script>

    <!--JS Loading block-->
    {% block js %}
    {% endblock %}
</body>
</html>

block blocks defined in base.html can be overwritten in inherited pages

extend.html

```html
<!-- Declare that the current page inherits from base -->
{% extends 'base.html' %}

{% block title %}NewTitle{% endblock %}

{% block content %}
<p>NewHtml</p>
{% endblock %}

{% block js %}
<script src="/static/js/add.js"></script>
{% endblock %}
  1. Macro macro

Using macros, you can define a function used in html, which takes parameters, returns values (content processing) or text (dynamic elements). We can put commonly used functions in an HTML file and import them where they need to be used.

  1. Define a macro set'_macro.html'
{# Define a dynamically generated input element #}
{% macro input(name,value='',type='text',size=20) %}
    <input type="{{ type }}"
        name="{{ name }}"
        value="{{ value }}"
        size="{{ size }}"/>
{% endmacro %}

  1. Use macros
{% import '_macro.html' as macro %}

<label for="username">User name:</label>
{{ macro.input('username') }}
  1. Customize global functions

Custom global functions are defined in python files and passed into the template using the'add_template_global'method

  1. Define a global function
def time_format(str_time):
    return str_time.sub[0: 10]

app.add_template_global(time_format, "time_format")
  1. Use in html
{% time_new = time_format("2018-01-01 09:33:24") %}
<p>{{ time_new }}</p>

Posted by cdhogan on Mon, 30 Sep 2019 11:20:17 -0700