Heim > Fragen und Antworten > Hauptteil
通过python处理出来的文本保存到一个列表中
列表在这,列表嵌套字典
[{'name': 'tom', 'class': '12', 'age': '8', 'flag': 'chn'}, {'name': 'mike', 'class': '11', 'age': '9', 'flag': 'en'}, {'name': 'jim', 'class': '2', 'age': '7', 'flag': 'chn'}]
html代码如下
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>表格</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
</head>
<body>
<h1>表格</h1>
<table class="table table-striped">
<thead>
<tr>
<th>name</th>
<th>class</th>
<th>age</th>
<th>flag</th>
</tr>
</thead>
<tbody>
<tr>
<td>表格单元格</td>
<td>表格单元格</td>
<td>表格单元格</td>
<td>表格单元格</td>
</tr>
<tr>
<td>表格单元格</td>
<td>表格单元格</td>
<td>表格单元格</td>
<td>表格单元格</td>
</tr>
<tr>
<td>表格单元格</td>
<td>表格单元格</td>
<td>表格单元格</td>
<td>表格单元格</td>
</tr>
</tbody>
</table>
</body>
</html>
初学flask,想把一个列表里面嵌套的字典遍历到web上,web上是一个表格,多谢
高洛峰2017-04-18 09:07:31
http://dormousehole.readthedocs.io/en/latest/tutorial/templates.html#show-entries-html
<ul class=entries>
{% for entry in entries %}
<li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}
{% else %}
<li><em>Unbelievable. No entries here so far</em>
{% endfor %}
</ul>
大家讲道理2017-04-18 09:07:31
#coding:utf-8
from flask import Flask
# 下面两个是给表格用的
from flask_table import Table, Col
from flask import render_template
from flask_sqlalchemy import SQLAlchemy
# import things
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///database.db'
db=SQLAlchemy(app)
class ItemModel(db.Model):
name=db.Column(db.String(255),primary_key=True)
description=db.Column(db.String(255))
# 生成数据库实例
db.create_all()
add_item=ItemModel(name='yoyo3',description='handsome')
db.session.add(add_item)
db.session.commit()
# 继承table表
class ItemTable(Table):
# 这个是保留字 会给table增加class属性
classes = ['table','table-border','table-sriped','table-hover','table-condensed']
# 这个表两个列
name = Col('Name')
description = Col('Description')
# 这个是要传输的数据 这个一下 可以在测试的时候用
# items = [dict(name='Name1', description='Description1'),
# dict(name='Name2', description='Description2'),
# dict(name='Name3', description='Description3')]
# 这个以上
# 如果传输的是数据库的话 可以用这个 正式用的时候可以用这个
# 不知道itemModel是什么的 看一下orm
items = ItemModel.query.all()
# 这个是itemTable的实例
table = ItemTable(items)
@app.route('/')
def hello_world():
return render_template(
'home.html',
# 把table传输给view了
table=table
)
# 显示输出 测试用的
print(table.__html__())
if __name__ == '__main__':
app.run()