Flask中jinja2的应用

Flask中jinja2的应用

# -*- coding: utf-8 -*-
# @Time    : 2019/9/24 17:29
# @Author  : AnWen
from flask import Flask, render_template

app = Flask(__name__)
app.debug = True
# 数据
STUDENT = {'name': 'Old', 'age': 38, 'gender': '中'}
STUDENT_LIST = [
	{'name': 'Old', 'age': 38, 'gender': '中'},
	{'name': 'Boy', 'age': 73, 'gender': '男'},
	{'name': 'EDU', 'age': 84, 'gender': '女'}
]
STUDENT_DICT = {
	1: {'name': 'Old', 'age': 38, 'gender': '中'},
	2: {'name': 'Boy', 'age': 73, 'gender': '男'},
	3: {'name': 'EDU', 'age': 84, 'gender': '女'},
}


def func(a, b):
	return a + b


@app.route('/stu')
def stu():
	return render_template('stu.html', func=func ,stu_info=STUDENT, stu_list=STUDENT_LIST, stu_dic=STUDENT_DICT)


if __name__ == '__main__':
	app.run()

html文件

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<h1>haha</h1>
{{ stu_info }}
<table border="1">
  <thead>
  <tr>
    <td>name</td>
    <td>age</td>
    <td>gender</td>
  </tr>
  </thead>
  <tbody>
  <tr>
    <td>{{ stu_info.name }}</td>
    <td>{{ stu_info.age }}</td>
    <td>{{ stu_info["gender"] }}</td>
  </tr>
  </tbody>
</table>

{{ stu_list }}
<table border="1px">
  <thead>
  <tr>
    <td>name</td>
    <td>age</td>
    <td>gender</td>
  </tr>
  </thead>
  <tbody>
  {% for stu in stu_list %}
    <tr>
      <td>{{ stu.name }}</td>
      <td>{{ stu.get('age') }}</td>
      <td>
        {% if stu["gender"] !="男" and stu['gender'] !="女" %}
          alal
        {% else %}
          {{ stu["gender"] }}
        {% endif %}
      </td>
    </tr>
  {% endfor %}

  </tbody>
</table>


{{ stu_dic }}
{% for dic in stu_dic %}
  {{ stu_dic[dic].get("name") }}
  {{ stu_dic[dic]["age"] }}
  {{ stu_dic[dic].gender }}
{% endfor %}


<table border="1px">
  <thead>
  <tr>
    <td>id</td>
    <td>name</td>
    <td>age</td>
    <td>gender</td>
  </tr>
  </thead>
  <tbody>
  {% for key,item in stu_dic.items() %}
    <tr>
    <td>{{ key }}</td>
    <td>{{ item.name }}</td>
    <td>{{ item.age }}</td>
    <td>{{ item.gender }}</td>
  </tr>
  {% endfor %}

  </tbody>
</table>

<p>{{ func(2,3) }}</p>

{% macro my_input(type,name) %}
  <input type="{{ type }}" name="{{ name }}">
{% endmacro %}
<p>自己创建的input标签 :{{ my_input("text","username") }} {{ my_input("password","pass") }} {{ my_input("file","myfile") }}</p>
</body>
</html>
posted @ 2019-09-25 08:06  爱文飞翔  阅读(801)  评论(0编辑  收藏  举报