Flask 在模板中包含具有类似视图逻辑的代码段

Flask 在模板中包含具有类似视图逻辑的代码段,flask,flask-flatpages,Flask,Flask Flatpages,我正在建立一个网页博客。在减价博客帖子的标题中,我按文件名列出了相关的博客帖子。这些应该显示为实际博客帖子下面的摘录 以下是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 am

我正在建立一个网页博客。在减价博客帖子的标题中,我按文件名列出了相关的博客帖子。这些应该显示为实际博客帖子下面的摘录

以下是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
重要的部分是遵循相关博客帖子的路径,呈现它们的标题和例外。天真地说:

{% for item in blog.meta.related %}
    <div>
    <h4>{{ item.title }}</h4>
    <p>{{ item.decription</p>
    </div>
{% endfor %}
我的问题是:如何在同一个模板中实现这一点


我是否应该设法将相关博客帖子中的数据传递到上下文中:可能是一个目录列表?我应该使用上下文处理器来实现这一点吗?

我得出了一个非常简单的答案,但问题仍然存在,看看是否有更优雅的解决方案

在view函数中,我迭代相关博客帖子的路径,并将博客对象添加到列表中,该列表将传递给模板

像这样:

@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 %}

Hei Roy,谢谢你的研究,但目前我无法发表评论,所以我必须想办法澄清这一点

为了使其正常工作,在您编写的标记文件中:

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.
需要在没有.md扩展名的情况下更改blogpost-2.md和blogpost-4.md。 在视图文件上循环时,如果没有这些更改:

for path in blog.meta['related']:
        related_list.append(blogs.get_or_404(path))
blogpost-1/2.md将不会添加到您的列表中,因为页面无法理解。出现了md扩展名和404错误

就我而言

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

{{ related.title }}
您可以通过以下链接添加到相关文章:

<a href="{{ url_for('site.bloging', path=related.path) }}">{{ related.title }}</a>
我的蓝图在哪里

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