2017-05-16 22 views
0

我正在用烧瓶平板页构建博客。在减价blogpost的标题中,我按照文件名列出了相关的博客帖子。这些应显示为实际博客下面的摘录。在包含片段的模板中包含类似于视图的逻辑

这里是blogpost-1.md应该是这样的:

title: "Blogpost one" 
published: 2014-02-13 
related: 
    - blogpost-2.md 
    - blogpost-4.md 
description: "This is the excerpt of blogpost one." 

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer 
vel leo turpis. Cras vulputate mattis dignissim. Aliquam eget 
purus purus. 

而结果我想:

BLOGPOST ONE 

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer vel 
leo turpis. Cras vulputate mattis dignissim. Aliquam eget purus purus. 

related posts: 

BLOGPOST TWO 
Summary here 

BLOGPOST THREE 
Also a summary 

的重要组成部分,是按照相关blogpostings的路径和渲染他们的头衔和除外。天真是这样的:

{% for item in blog.meta.related %} 
    <div> 
    <h4>{{ item.title }}</h4> 
    <p>{{ item.decription</p> 
    </div> 
{% endfor %} 

这显然是行不通的,因为meta.related仅仅是一个字符串列表。这也不难作出这样的对待这些字符串并返回一个HttpResponse对象视图功能:

# app.py 
@app.route('/excerpt/<path:path>.html') 
def excerpt(path): 
    blog = blogs.get_or_404(path) 
    return render_template('excerpt.html', blog=blog) 

# excerpt.html 
<div> 
<h4>{{ blog.meta.title }}</h4> 
<p>{{ blog.meta.description }}</p> 
</div> 

我的问题:如何使这种情况发生在同一模板内?

我是否应该以某种方式尝试将相关博客的数据传递到上下文中:可能是一个dicts列表?我应该使用上下文处理器来实现吗?

回答

1

喜罗伊,感谢您的研究,但目前我不能发表评论,所以我必须找到一种方法来澄清这。

为了使这一工作,在降价文件,你写道:

title: "Blogpost one" 
published: 2014-02-13 
related: 
- blogpost-2.md 
- blogpost-4.md 
description: "This is the excerpt of blogpost one." 

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer 
vel leo turpis. Cras vulputate mattis dignissim. Aliquam eget 
purus purus. 

需要被改变blogpost-2.md和blogpost-4.md没有.MD扩展。 没有这些变化,当你在循环视图文件:

for path in blog.meta['related']: 
     related_list.append(blogs.get_or_404(path)) 

博文-1/2.md 将不会添加到你的列表中,因为烧瓶的flatpages不会明白.MD延伸和404错误出现。

在我的情况

@app.route('/blog/<path:path>.html') 

而没有改变。HTML这样的:

@site.route('/bloging/<path:path>/') 

,并简化一些编码,在模板

{{ related.meta.title }} 

相当于

{{ related.title }} 

,你可以链接与添加到您的相关文章:

<a href="{{ url_for('site.bloging', path=related.path) }}">{{ related.title }}</a> 

其中si te是我的蓝图。

0

我得到了一个非常简单的答案,但保持这个问题是否有一个更优雅的解决方案。

在视图函数中,我遍历相关博客文章的路径,并将博客对象添加到传递给模板的列表中。

像这样:

@app.route('/blog/<path:path>.html') 
def blog_detail(path): 
    blog = blogs.get_or_404(path) 
    related_list = [] 
    for path in blog.meta['related']: 
     related_list.append(blogs.get_or_404(path)) 
    return render_template('blog-detail.html', blog=blog, related_list=related_list) 

而且在模板:

{% for related in related_list %} 
    hoi 
    <div> 
     <h4>{{ related.meta.title }}</h4> 
     <p>{{ related.meta.description }}</p> 
    </div> 
{% endfor %}