Python 在jinja2模板中创建指向Flask应用程序url的链接

Python 在jinja2模板中创建指向Flask应用程序url的链接,python,flask,jinja2,url-for,Python,Flask,Jinja2,Url For,在我的Flask应用程序中,我有一个显示帖子的视图 @post_blueprint.route('/post/<int:year>/<int:month>/<title>') def get_post(year,month,title): # My code 现在,当我显示最后10篇文章时,我想将一篇文章的标题转换为超链接。 目前,我必须在我的jinja模板中执行以下操作以实现此目标: <a href="/post/{{year}}/{{mon

在我的Flask应用程序中,我有一个显示帖子的视图

@post_blueprint.route('/post/<int:year>/<int:month>/<title>')
def get_post(year,month,title):
    # My code
现在,当我显示最后10篇文章时,我想将一篇文章的标题转换为超链接。 目前,我必须在我的jinja模板中执行以下操作以实现此目标:

<a href="/post/{{year}}/{{month}}/{{title}}">{{title}}</a>

我试过找一个,但找不到。

我觉得你在问两个问题,但我想试试

对于发布url,您可以执行以下操作:

<a href="{{ url_for('post_blueprint.get_post', year=year, month=month, title=title)}}">
    {{ title }}
</a>
如果您想了解更多信息,我强烈建议您阅读。及

编辑以使用kwargs:

只是觉得我会更彻底

如果您想像这样使用
url\u

url_for('view_name',**arguments)
{{ url_for('post_blueprint.get_post', **post) }}
@post_blueprint.route('/posts/')
def get_all_posts():
    models = database_call_of_some_kind # This is assuming you use some kind of model
    posts = []
    for model in models:
        posts.append(dict(year=model.year, month=model.month, title=model.title))
    return render_template('p.html', posts=posts)
{% for post in posts %}
    <a href="{{ url_for('post_blueprint.get_post', **post) }}">
        {{ post['title'] }}
    </a>
{% endfor %}
您必须将视图更改为以下内容:

url_for('view_name',**arguments)
{{ url_for('post_blueprint.get_post', **post) }}
@post_blueprint.route('/posts/')
def get_all_posts():
    models = database_call_of_some_kind # This is assuming you use some kind of model
    posts = []
    for model in models:
        posts.append(dict(year=model.year, month=model.month, title=model.title))
    return render_template('p.html', posts=posts)
{% for post in posts %}
    <a href="{{ url_for('post_blueprint.get_post', **post) }}">
        {{ post['title'] }}
    </a>
{% endfor %}
然后,您的模板代码可以如下所示:

url_for('view_name',**arguments)
{{ url_for('post_blueprint.get_post', **post) }}
@post_blueprint.route('/posts/')
def get_all_posts():
    models = database_call_of_some_kind # This is assuming you use some kind of model
    posts = []
    for model in models:
        posts.append(dict(year=model.year, month=model.month, title=model.title))
    return render_template('p.html', posts=posts)
{% for post in posts %}
    <a href="{{ url_for('post_blueprint.get_post', **post) }}">
        {{ post['title'] }}
    </a>
{% endfor %}
{%for posts in posts%}
{%endfor%}

在这一点上,我实际上会在模型上创建一个方法,这样您就不必将其转换为dict,但这取决于您:-)。

那么您希望使用url\u来使用kwargs?要做到这一点,唯一的办法就是把帖子列为一个目录。我不相信在不改变视图中的逻辑的情况下,有什么方法可以做到这一点。什么是
模型
类型,为什么我们需要将其转换为dict?我们不能将它传递到视图并在那里迭代吗?