43

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

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

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

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

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

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

有什么办法可以避免对网址进行硬编码?

url_for这样用于创建 Flask url 的函数:

url_for('view_name',**arguments)

我已经尝试寻找一个,但我无法找到它。

4

1 回答 1

83

I feel like you're asking two questions here but I'll take a shot...

For the posting url you'd do this:

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

To handle static files I'd highly suggest using an asset manager like Flask-Assets, but to do it with vanilla flask you do:

{{ url_for('static', filename='[filenameofstaticfile]') }}

If you'd like more information I highly suggest you read. http://flask.pocoo.org/docs/quickstart/#static-files and http://flask.pocoo.org/docs/quickstart/#url-building

Edit for using kwargs:

Just thought I'd be more thorough...

If you'd like to use url_for like this:

{{ url_for('post_blueprint.get_post', **post) }}

You have to change your view to something like this:

@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)

Then your template code can look like this:

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

At this point I would actually create a method on the model so you don't have to turn it into a dict, but going that far is up to you :-).

于 2012-06-20T17:41:25.380 回答