如何访问 html 模板 url_for 中的变量

How to access variables within html template url_for

我正在为我的 Devops 课程构建一个类似 Netflix 的网站。我制作了一个 Python 词典列表 (Mockfilms) 来定义我的电影,并希望用评论填充数据库 (Ratings) 以准备以 :filmid: :userid: :rating: 格式发送数据到推荐引擎。

我的索引页是一个电影图像列表,每个图像下面都有一个 link 评论表。我希望每个评论表单出现在不同的 url 上(/review/ID,其中 ID 在 mockfilms 中保存为 oid)。为此,我想访问 mockfilms.oid,然后将其传递给视图函数以创建表单的 url。表单完成后,我想将此 ID 添加到评级数据库中。这是我目前所拥有的:

索引:

{% extends "base.html" %}

{% block content %}
    <h1>Hello, {{ current_user.username }}! Welcome to our extensive video library:</h1>
    {% for film in mockfilms %}
    {% set ID = film.oid %}
    <div>
        <a href = {{ film.video }}>
            <img src = {{ film.image }} alt = "doh" style = "width:200px;height:200px;border:0;">
        </a>
    </div>
    <div>

        <a href={{ url_for('review', ID) }}"> ">Leave a review here!</a>
    {% endfor %}
{% endblock %}

路线:

@app.route('/review/<ID>', methods = ['GET', 'POST'])
@login_required
def review(ID):
    form = ReviewForm()
    if form.validate_on_submit():
        review = Ratings(User_id = current_user.id, Score_given = form.score.data, Film_id = ID)
        db.session.add(review)
        db.session.commit()
        flash('Thanks for your review')
        return redirect(url_for('index'))
    return render_template('review.html', title='Review Page', form=form)

以下错误是我在 运行 时得到的:

文件“/home/jc/Desktop/Lokal/DevopsAssig/microblog/Kilfinnan/lib/python3.5/site-packages/werkzeug/routing.py”,第 1768 行,在构建中 提高 BuildError(端点、值、方法、自我) werkzeug.routing.BuildError:无法为端点 'review' 构建 url。您是否忘记指定值 ['ID']?

据此我假设问题出在该模板中的 ID 变量上。我的搜索和学习让我相信索引模板中的 {% set %} 可以让我声明 ID 变量,然后在动态中使用它。

尝试为您的 url_for 函数提供 key=value 个参数。

像这样

<a href={{ url_for('review', ID=ID) }}"> ">Leave a review here!</a>

另外 Flask 有很棒的文档,Flask docs

试试这个:

{% block content %}
    <h1>
        Hello, {{ current_user.username }}! 
        Welcome to our extensive video library:
    </h1>
    {% for film in mockfilms %}
    <div>
        <a href="{{ film.video }}">
            <img src="{{ film.image }}" alt="doh" style="width:200px;height:200px;border:0;" />
        </a>
    </div>
    <div>
        <a href="{{ url_for('review', ID=film.oid) }}">
            Leave a review here!
        </a>
    </div>
    {% endfor %}
{% endblock %}

最终您的解决方案非常接近,但是当您需要使用关键字作为参数将变量传递到 url_for() 函数时,没有必要使用 Jinja set 命令。你仍然可以使用 {% set ID = film.oid %} 来完成它,但它有点多余。