首页 文章

如何使用Flask和Jinja2使某些HTML不显示?

提问于
浏览
0

我正在创建一个Flask应用程序,它从用户那里获取一个输入,然后使用该输入来查询API,并返回结果 .

我正在尝试使用相同的模板来获取用户输入并显示结果 .

我的返回渲染模板如下所示:

return render_template("query.html", json_data=json_data, info=info)

问题是,当页面首次加载时,它正在寻找 json_datainfo 变量,但它们还不存在 .

我试过这样做:

data = request.args.get("t")

    if data:
        ...
        return render_template("query.html", json_data=json_data, info=info)

    else:

        return render_template("meter_mdm.html", json_data=None, info=None)

然后在我的Jinja模板中,我把:

{% if json_data is not none and info is not none %}   

    ...HTML that uses the json_data and info variables

{% endif %}

但它仍然在 if 语句之间加载数据 .

知道我需要做什么来在同一页面上加载结果吗?

1 回答

  • 1

    尝试简化此行:

    {% if json_data is not none and info is not none %}
    

    至:

    {% if json_data and info %}
    

    这是一个有用的演示:

    视图:

    app.route('/')
    def index():
        name = None
        age = None
    return render_template('index.html', name=name, age=age)
    

    index.html的:

    {% if name and age %}
    Hello, boy!
    {% endif %}
    

相关问题