bem*_*3ry 17 html python jinja2 flask
我在使用Python生成html文档时遇到了一些问题.我正在尝试创建目录树的HTML列表.这是我到目前为止:
def list_files(startpath):
for root, dirs, files in os.walk(startpath):
level = root.replace(startpath, '').count(os.sep)
if level <= 1:
print('<li>{}<ul>'.format(os.path.basename(root)))
else:
print('<li>{}'.format(os.path.basename(root)))
for f in files:
last_file = len(files)-1
if f == files[last_file]:
print('<li>{}</li></ul>'.format(f))
elif f == files[0] and level-1 > 0:
print('<ul><li>{}</li>'.format(f))
else:
print('<li>{}</li>'.format(f))
print('</li></ul>')
Run Code Online (Sandbox Code Playgroud)
如果只有根目录,一级子目录和文件,它似乎运行良好.但是,添加另一级别的子目录会导致出现问题(因为我认为close标签在结束时输入的次数不够多).但是我很难理解它.
如果不能这样做,有没有更简单的方法呢?我正在使用Flask,但我对模板缺乏经验,所以也许我错过了一些东西.
jfs*_*jfs 40
您可以将目录树生成及其呈现分离为html.
要生成树,您可以使用简单的递归函数:
def make_tree(path):
tree = dict(name=os.path.basename(path), children=[])
try: lst = os.listdir(path)
except OSError:
pass #ignore errors
else:
for name in lst:
fn = os.path.join(path, name)
if os.path.isdir(fn):
tree['children'].append(make_tree(fn))
else:
tree['children'].append(dict(name=name))
return tree
Run Code Online (Sandbox Code Playgroud)
要将其渲染为html,您可以使用jinja2的循环recursive功能:
<!doctype html>
<title>Path: {{ tree.name }}</title>
<h1>{{ tree.name }}</h1>
<ul>
{%- for item in tree.children recursive %}
<li>{{ item.name }}
{%- if item.children -%}
<ul>{{ loop(item.children) }}</ul>
{%- endif %}</li>
{%- endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)
将html放入templates/dirtree.html文件中.要测试它,请运行以下代码并访问http://localhost:8888/:
import os
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def dirtree():
path = os.path.expanduser(u'~')
return render_template('dirtree.html', tree=make_tree(path))
if __name__=="__main__":
app.run(host='localhost', port=8888, debug=True)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11379 次 |
| 最近记录: |