jinja2.exceptions.UndefinedError对于从Flask模板传递给python函数的变量

时间:2019-03-19 09:02:15

标签: flask jinja2

我收到此错误jinja2.exceptions.UndefinedError: 'values' is undefined。我在Flask网站http://flask.pocoo.org/docs/0.12/templating/上引用的简单代码如下:

@app.context_processor
def utility_processor():
    def format_price(amount, currency=u'€'):
        return u'{0:.2f}{1}'.format(float(amount), currency)
    return dict(format_price=format_price)

@app.route("/file_t")
def file_t():

    return render_template('DB.html')


@app.route("/file_ttt", methods=['POST'])
def file_ttt():

    if request.method == 'POST':
        bMultyTest_plot = request.values.get("bMultyTest_plot")
        print(bMultyTest_plot)

        return jsonify({'result': 'success', 'value': 0.44})

以及下面的html模板代码:

<button type="button" onclick="visualize()">Visualize</button>
<div id='here'></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
    function visualize()
    {
        req = $.ajax({
            url : "/file_ttt",
            type: "POST",
            data: {"bMultyTest_plot": true}
        })

        req.done(function(data) {
            var values = data.value;
             document.getElementById("here").innerHTML ="{{format_price(values)}}";
        });
    }   
</script>

如果我传递一个浮点值,那么该函数将起作用,而不是变量值。喜欢:

 document.getElementById("here").innerHTML ="{{format_price(0.33)}}";

但是有一个变量,我得到以下错误:

document.getElementById("demo").innerHTML ="{{format_price(values)}}";
File "<ipython-input-138-4e2a0498745e>", line 17, in format_price
return u'{0:.2f}{1}'.format(float(amount), currency)
jinja2.exceptions.UndefinedError: 'values' is undefined
10.45.65.219 - - [19/Mar/2019 09:56:12] "GET /file_t HTTP/1.1" 500 -    

1 个答案:

答案 0 :(得分:0)

您的模板需要values变量,但是在render_template中调用file_t函数时不提供该变量。您需要像这样提供它:

return render_template('DB.html', values=values)

有关更多信息,请参见the documentation