Python を学習していると同時に、マークダウン ファイルを読み取る簡単なフラスコ ブログを作成しています。これらのファイルは、タイトル、日付、およびスラッグを含む yaml ファイルにマップされます。
すべての投稿をマップする yaml ファイル [posts.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
---
ファイル名が yaml ファイル [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 %}
もう 1 つの問題は、最後の投稿 (日付順) を最初のページに表示することです。この情報は、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')
助けてくれてありがとう!