python + django 搭建网页(尝试4):自动显示txt文件
我想实现:
程序自动从一个文件夹中读取文档,然后呈现在一个网页上。
1. urls.py 设置
urls.py 中:
urlpatterns = [
...
path('loveread/pandawarrior/', views.collection, {'author': "熊猫酒仙"}),
...
]
这样,访问到 .../loveread/pandawarrior/ 地址的时候,就启动 views.py 中的 colloection 函数,并且传入参数 author = "熊猫酒仙"。
2. views.py 设置
定义 collection 函数,查看 statics/works/熊猫酒仙/ 路径下的所有文件,然后将所有文件的内容载入到 content 列表中。
最后将作者名通过 author, 内容通过 content 传给 context 变量,再将 context 的值传递给 render 函数。由 render 函数读取 template/collection.html 模板,生成网页。
def collection(request, author):
print("author = ", author)
dir = "statics/works/" + author + "/"
filenames = os.listdir(dir)
print("filenames = ", filenames)
content = []
for filename in filenames:
content += [ line for line in open(dir+filename, 'r', encoding='UTF-8')]
print("open = ", open(dir+filename, 'r', encoding='UTF-8') )
content += [" "," "]
print("content = ", content)
context = {
'author': author,
'content': content,
}
return render(request, 'collection.html', context)
3. 模板 collection.html
自动显示 xxx 作品集,然后把前面从 statics/works/熊猫酒仙/路径下所有文档中读取的内容显示在一个页面上。
{{author}}
{{author}}作品集
{% for i in content %}
{{ i |safe }}
{% endfor %}
4. 效果图
5. 总结与展望
- 现在可以搭建很简单的个人文集网页,每次更新只需要向相应文件夹补充作品txt,网页就会自动更新。
- 展望:目前网页还非常简陋,没有经过精心的排版、渲染、字体等调节。未来可能借鉴别人的html页面,修改我们的 html 模板。