如何使用Jinja2
从列表中动态生成表单输入和标签?例如,假设我有列表:
A = ["name", "city", "state","phone"]
B = ["album", "artist", "genre"]
C = ["title","author","category", "subcategory"]
标有A
,B
和C
的按钮。我想根据点击的按钮动态生成表单。因此,如果单击B
,我想使用B中的项来动态生成:
<form>
<div class="form-group row">
<label for="album" class="col-2 col-form-label">album</label>
<div class="col-10">
<input class="form-control" type="text" id="album">
</div>
</div>
<div class="form-group row">
<label for="artist" class="col-2 col-form-label">artist</label>
<div class="col-10">
<input class="form-control" type="text" id="artist">
</div>
</div>
<div class="form-group row">
<label for="genre" class="col-2 col-form-label">genre</label>
<div class="col-10">
<input class="form-control" type="text" id="genre">
</div>
</div>
</form>
答案 0 :(得分:0)
如果我理解你的情况,我认为这是一个可行的解决方案。
Python示例文件:
from flask import Flask, render_template
app = Flask(__name__)
B = ["Ten","Pearl Jam","Grunge"]
@app.route('/')
def main():
return render_template('stuff.html', my_list=B)
if __name__ == '__main__':
app.run(debug=True, port=5000)
模板示例文件:
<!doctype html>
<title>Test</title>
<div class=page>
<h1>Data</h1>
<form>
<div class="form-group row">
<label for="album" class="col-2 col-form-label">{{my_list[0]}}</label>
<div class="col-10">
<input class="form-control" type="text" id="album">
</div>
</div>
<div class="form-group row">
<label for="artist" class="col-2 col-form-label">{{my_list[1]}}</label>
<div class="col-10">
<input class="form-control" type="text" id="artist">
</div>
</div>
<div class="form-group row">
<label for="genre" class="col-2 col-form-label">{{my_list[2]}}</label>
<div class="col-10">
<input class="form-control" type="text" id="genre">
</div>
</div>
</form>
</div>
for循环的模板示例:
<!doctype html>
<title>Test</title>
<div class=page>
<h1>Data</h1>
{% for item in my_list %}
<li>{{item}}</li>
{% endfor %}
</div>