-1

I'm learning python and at the same time, I'm creating a simple flask blog the reads markdown files. These files are mapped with a yaml file that has the title, the date and the slug.

The yaml file that maps all posts [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
---

The example of a markdown post, where the file name matches the slug in the yaml file [title-of-a-post.md]:

title: title of a posts
date: 10/10/2012
slug: title-of-a-post

The text of the post...

I already can read and present the markdown file. I can generate the links from the yaml file, what I'm fight right now is after reading the yaml file, supposing I have 10 posts, how can I show only the last 5 posts/links?

I'm using a FOR IN loop to show all links, but I only want to show the last 5. How can I accomplish that?

{% for doc in docs if doc.type == 'post' %}
        <li><a href="{{ url_for('page', file = doc.slug) }}">{{ doc.title }}</a></li>
{% endfor %}

The other problem is getting the last post (by date) to show in the fist page. This information should be returned from the yaml file.

At the top of the yaml file, I have the last post, so the posts are ordered by date descendant.

This is the flask file:

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')

Thanks for you help!

4

1 回答 1

1

检出Jinja2(Flask 的默认模板库)关于Loop Control的文档,内置FiltersControl Structures

你感兴趣的是:

您可以使用普通(真棒!)Python 切片语法,例如

for doc in docs[:5]
    # Only loops over the first 5 items...

我看到posts.yaml有一个type,如果您混合非“post”类型,循环会变得更加复杂。您可能需要考虑避免模板中的繁重排序/过滤/逻辑。

希望这能让你走上正轨。

于 2013-10-22T18:20:28.650 回答