Flask template detailed description and examples

																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																											## Flask模板

1. Jinja2 and rendering method

The matching template for Flask is jinja2, the same author

Use rander_template to render templates, all templates are placed in templates, rander_template (file name, content to be rendered), use { {}} to read the content in the database in the web page .

View content

from flask import Flask, render_template

#创建Flask对象
app = Flask(__name__)
#需要渲染的内容,此部分内容一般从数据库中抓取
content = {
    
     
	'name':'kk',
	'age':18,
	'sex':1

@app.route('/')
def index():
	return render_template('index.html', **content)

Web code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>{
    
    {
    
    name}}</h1>
    <h2>{
    
    {
    
    age}}</h2>
    <h3>{
    
    {
    
    sex}}</h3>
</body>
</html>

2. Template filter

The template filter can make some judgments on some data passed from the backend.
Usually use the pipe symbol |. Such as { {variable|condition}}
view content

from flask import Flask, render_template

app = Flask(__name__)
#此参数设定后,只要模板变化,flask会自动刷新
app.config['TEMPLATES_AUTO_RELOAD'] = True


content = {
    
    
    'name': 'kML',
    'age': 20.5,
    'books': {
    
    
        'python': 30,
        'java': 20,
        'php': 10,
        'flask': -50
    },
    'input_content': '<input type = "text"  name ="text">'
}

@app.route('/')
def index():
	return render_template('index.html', **content)

index.html template content

<div>
    <p>
        {
    
    # default 判断,若不存在username,则显示加载中 #}
        {
    
    {
    
    username|default('加载中')}}
    </p>
    <p>
        {
    
    # 计算input_content长度 #}
        {
    
    {
    
    input_content|length}}
    </p>
    <p>
        {
    
    # 关闭转义,再已确认input_content安全的情况下#}
        {
    
    {
    
    input_content|safe}}
    </p>
    <p>
        {
    
    # 系统默认转义打开,故此e/escape只有在转义关闭的时候使用 #}
        {
    
    {
    
    input_content|e}}
    </p>
    <p>
        {
    
    # replace(old,new),old表示name中存在的部分,new表示新的内容 #}
        {
    
    {
    
    name|replace('k','l')}}
    </p>
    <p>
        {
    
    # first:返回一个序列的第一个元素 #}
        {
    
    {
    
    name|first}}
    </p>
    <p>
        {
    
    # last:返回序列的最后一个元素 #}
        {
    
    {
    
    name|last}}
    </p>
    <p>
        {
    
    # join:将一个序列用d这个参数的值拼接成字符串,最后显示为k_m_l。 #}
        {
    
    {
    
    name|join(d='_')}}
    </p>
    <p>
        {
    
    # int:将值转换为int类型。 #}
        {
    
    {
    
    age|int}}
    </p>
    <p>
        {
    
    # float:将值转换为浮点数类型。 #}
        {
    
    {
    
    age|float}}
    </p>
    <p>
        {
    
    # lower:将字母转为小写。 #}
        {
    
    {
    
    name|lower}}
    </p>
    <p>
        {
    
    # upper:将字母转为大写。 #}
        {
    
    {
    
    name|upper}}
    </p>
    <p>
        {
    
    # truncate:截取length长度的字符串,length:表示显示长度,killwords:表示是否截断单词,leeway:偏差。 #}
        {
    
    {
    
    input_content|truncate(length=5,killwords=False,leeway=0)}}
    </p>
</div>

4. Control statements

Control statements are written in {% xxx %}, for and if statements must end with end,
such as:
{% for item in items %}
{% endfor %}


{% if condition%}
{% elif condition%}
{% else %}
{% endif %}

4.1, for loop

The view content is consistent with the view content in 2

<div>
    {
    
    # for循环读字典内容 #}}
    <table>
        <tr>
            <td>序号</td>
            <td>书名</td>
            <td>价格</td>
        </tr>
        <tr>
            {
    
    % for key,value in books.items() %}
            {
    
    # loop.length:序列长度。loop.first/last:是否第一次/最后一次迭代,返回True或False #}
            {
    
    # loop.index:从1开始迭代。loop.index0:从0开始迭代 #}
            <th> {
    
    {
    
    loop.index}}</th>
            <th>{
    
    {
    
     key }}</th>
            <th>{
    
    {
    
     value|abs }}</th>
            <tr>
            {
    
    % endfor %}
        </tr>
    </table>
</div>
4.2, if judgment

The view content is consistent with the view content in 2

<div>
    {
    
    # if判断 #}
    <p>年龄多少:
        {
    
    % if age > 18 %}
            {
    
    {
    
    age}}
        {
    
    % else %}
            '不存在'
        {
    
    % endif %}
    </p>
</div>
4.3, macro and import import

The macro is carried in the text in html format, which is equivalent to defining a functional function. The html text can be imported at any time and reused.

#forms.html语法
{
    
    % macro 名称(变量1,变量2,变量3) %}
	{
    
    % for item in range(0,变量1) %}
		<input type="text">
	{
    
    % endfor %}
{
    
    % endmacro %}
#在html的界面中导入forms.html
{
    
    % from 'forms.html' import 名称 %}
{
    
    {
    
    名称(3)}}
4.4, include and set statements

The include statement introduces a template into another template

{
    
    % include 'header.html' %}

The set statement adds a variable to the template. Variables in the
with statement can only take effect in with. Variables in the global and with variables do not affect each other

{
    
    % with %}
	{
    
    % set foo = 42 %}
	{
    
    {
    
     foo }}
{
    
    % endwith %}
#或者
{
    
    % with foo = 42 %}
    {
    
    {
    
     foo }}
{
    
    % endwith %}
4.5, template inheritance

The template in Flask is defined by block. As long as the parent template has a block interface, the child template can be rewritten by block or added on the original basis.

format

{
    
    % extends "base.html" %}
{
    
    % block 名称 %}
<h1>xxx</h1>
{
    
    % endblock %}

Parent template

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> {
    
    % block title %}
    {
    
    % endblock %} </title>
</head>
<body>
    {
    
    % block header %}
        <h1>base-header</h1>
    {
    
    % endblock %}
    {
    
    % block center %}
        <p>base-content</p>
    {
    
    % endblock %}
    {
    
    % block footer %}
        <h6>base-footer</h6>
    {
    
    % endblock %}
</body>
</html>

Subtemplate

{
    
    % extends "base.html" %}
{
    
    % block center %}
    <p>这是content</p>
{
    
    % endblock %}
{
    
    % block footer%}
    <h6>{
    
    {
    
    name|upper}}</h6>
    <p>
        {
    
    % for item in books.item %}
        {
    
    % end for %}
    </p>
{
    
    % endblock %}

Guess you like

Origin blog.csdn.net/qq_37697566/article/details/105635190