2013-10-22 45 views
0

我正在學習python,同時,我正在創建一個簡單的博客閱讀markdown文件。 這些文件與具有標題,日期和slu y的yaml文件進行映射。閱讀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 
--- 

一個降價後,該文件名在YAML文件中塞相匹配的例子[冠軍的-A柱.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

我不確定您的標題「在YAML中讀取第一個密鑰」是否真的很好地描述了您的實際問題。你的問題似乎與如何使用Jinja有關(儘管看起來你應該做的是在視圖中創建/排序5個元素的列表,然後將該列表傳遞給Jinja來顯示)。 –

回答

1

結賬Jinja2(Flask的默認模板庫)文件Loop Control,內置於FiltersControl Structures

您感興趣的是:

和正常(真棒!)的Python切片語法是提供給您,如

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

我見posts.yaml有一個type,如果你在非'post'類型混合,循環會變得更復雜一點。您可能想要考慮避免模板中的重排序/過濾/邏輯。

希望能讓你走上正軌。