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

cod*_*ool 35 python jinja2 url-for flask

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

@post_blueprint.route('/post/<int:year>/<int:month>/<title>')
def get_post(year,month,title):
    # My code
Run Code Online (Sandbox Code Playgroud)

要显示最后10个条目,我有以下视图:

@post_blueprint.route('/posts/')
def get_all_posts():
    # My code
    return render_template('p.html',posts=posts)
Run Code Online (Sandbox Code Playgroud)

现在,当我显示最后10个帖子时,我想将帖子的标题转换为超链接.目前我必须在我的jinja模板中执行以下操作来实现此目的:

<a href="/post/{{year}}/{{month}}/{{title}}">{{title}}</a>
Run Code Online (Sandbox Code Playgroud)

有没有办法避免硬编码网址?

就像url_for用于创建Flask网址的函数一样:

url_for('view_name',**arguments)
Run Code Online (Sandbox Code Playgroud)

我试过寻找一个,但我,我找不到它.

rav*_*c95 72

我觉得你在这里问两个问题,但我会拍一个......

对于发布网址,您可以这样做:

<a href="{{ url_for('post_blueprint.get_post', year=year, month=month, title=title)}}">
    {{ title }}
</a>
Run Code Online (Sandbox Code Playgroud)

为了处理静态文件,我强烈建议使用像Flask-Assets这样的资产管理器,但要使用vanilla flask,你可以:

{{ url_for('static', filename='[filenameofstaticfile]') }}
Run Code Online (Sandbox Code Playgroud)

如果您想了解更多信息,我强烈建议您阅读.http://flask.pocoo.org/docs/quickstart/#static-fileshttp://flask.pocoo.org/docs/quickstart/#url-building

编辑使用kwargs:

只是觉得我会更彻底......

如果你想这样使用url_for:

{{ url_for('post_blueprint.get_post', **post) }}
Run Code Online (Sandbox Code Playgroud)

您必须将视图更改为以下内容:

@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)
Run Code Online (Sandbox Code Playgroud)

然后你的模板代码看起来像这样:

{% for post in posts %}
    <a href="{{ url_for('post_blueprint.get_post', **post) }}">
        {{ post['title'] }}
    </a>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

在这一点上,我实际上会在模型上创建一个方法,所以你不必把它变成一个dict,但是走得那么远取决于你:-).

  • 什么是`models`类型以及为什么我们需要把它变成dict?我们不能将它传递给我们的视图并在那里迭代吗? (3认同)