我正在学习python,同时,我正在创建一个简单的烧瓶博客读取降价文件。 这些文件使用具有标题,日期和段塞的yaml文件进行映射。
映射所有帖子[posts.yaml]的yaml文件:
---
title: title of the last posts
date: 10/12/2012
slug: title-of-the-last-post
type: post
---
title: title of another posts
date: 10/11/2012
slug: title-of-another-post
type: post
---
title: title of a posts
date: 10/10/2012
slug: title-of-a-post
type: post
---
markdown帖子的示例,其中文件名与yaml文件中的slug匹配[title-of-a-post.md]:
title: title of a posts
date: 10/10/2012
slug: title-of-a-post
The text of the post...
我已经可以阅读并出示降价文件了。我可以从yaml文件生成链接,我现在正在阅读yaml文件,假设我有10个帖子,我怎么才能显示最后5个帖子/链接?
我正在使用FOR IN循环显示所有链接,但我只想显示最后5个。 我怎么能做到这一点?
{% for doc in docs if doc.type == 'post' %}
<li><a href="{{ url_for('page', file = doc.slug) }}">{{ doc.title }}</a></li>
{% endfor %}
另一个问题是在第一页显示最后一篇文章(按日期)。应该从yaml文件返回此信息。
在yaml文件的顶部,我有最后一篇文章,因此帖子按日期后代排序。
这是烧瓶文件:
import os, codecs, yaml, markdown
from werkzeug import secure_filename
from flask import Flask, render_template, Markup, abort, redirect, url_for, request
app = Flask(__name__)
# Configuration
PAGES_DIR = 'pages'
POSTS_FILE = 'posts.yaml'
app.config.from_object(__name__)
# Routes
@app.route('/')
def index():
path = os.path.abspath(os.path.join(os.path.dirname(__file__), app.config['POSTS_FILE']))
data = open(path, 'r')
docs = yaml.load_all(data)
return render_template('home.html', docs=docs)
@app.route('/<file>')
def page(file):
filename = secure_filename(file + '.md')
path = os.path.abspath(os.path.join(os.path.dirname(__file__), app.config['PAGES_DIR'], filename))
try:
f = codecs.open(path, 'r', encoding='utf-8')
except IOError:
return render_template('404.html'), 404
text = markdown.Markdown(extensions = ['meta'])
html = text.convert( f.read() )
return render_template('pages.html', **locals())
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0')
谢谢你的帮助!
答案 0 :(得分:1)
Loop Control上的Jinja2
(Flask的默认模板库)文档,内置于Filters和Control Structures。
您感兴趣的是:
reverse(seq)
函数(如果您的帖子按日期升序排序)。loop.index
or loop.index0
用于获取当前循环次数。first(seq)
用于从序列中提取第一项,当然还有last(seq)
. 正常(太棒了!)Python切片语法可供您使用,例如
for doc in docs[:5]
# Only loops over the first 5 items...
我看到posts.yaml
有一个type
,如果你混合非''''类型,循环会变得复杂一些。您可能想要考虑避免在模板中进行大量排序/过滤/逻辑。
希望能让你走上正轨。