首页 > 解决方案 > 为什么 render_template 没有被表达?

问题描述

我有一个使用 HTML 页面设置的工作烧瓶应用程序。问题是,在我拥有的 HTML 中{{ Appointments }},它总是显示render_template空列表的 second 的值。

@app.route("/PatientDashboard.html", methods=["GET", "POST"])
def PatientDashboard():

    if request.method == "POST":
        Date = request.form.get("Date")
        print(Date)
        return render_template("PatientDashboard.html", Appointments=["This should show up."])

    else:
        return render_template("PatientDashboard.html", Appointments=[]) 

问题是第一个render_template从未表达过。为什么会这样,我将如何解决它?

非常感谢你。

编辑1:

相关的 HTML 如下。

<script>
    var jsDate = $('#calendar').datepicker({
        inline: true,
        firstDay: 1,
        showOtherMonths: false,
        dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
        onSelect: function(dateText, inst) {
            document.getElementById("Date").innerHTML = dateText;
            $.ajax({
                type: 'POST',
                url: "{{ url_for('PatientDashboard') }}",
                data: {Date: dateText},
                dataType: "text",
            });
        }
    });
</script>

此外,我有{{ Appointments }}一个分隔线。

标签: pythonhtmlpostflask

解决方案


您正在将渲染模板的内容与Appointments您的 POST 请求的响应一起获取。如果您想Appointments在页面上使用数据,您需要使用回调扩展您的 POST 请求,该回调将使用该数据来满足您的任何需求。

所以基本上会发生什么:

  1. 页面加载(GET 请求),模板以空Appointments列表呈现
  2. 页面触发 POST ajax 请求,该请求返回带有Appointments集合的渲染模板
  3. 您没有处理 POST 响应,因此这些数据只是被丢弃。

典型的方法是从 POST 响应中仅获取相关数据(例如 JSON 格式),而不是整个页面:

from flask import Response

if request.method == "POST":
    Date = request.form.get("Date")
    print(Date)
    Appointments=["This should show up."]
    return Response(json.dumps(Appointments), mimetype='application/json')
else:
    return render_template("PatientDashboard.html", Appointments=[]) 

推荐阅读