2017-10-13 83 views
0

我對瓶的render_template()讀了,當我遇到的代碼塊來:瓶render_template()

@app.route('/result',methods = ['POST', 'GET']) 
def result(): 
    if request.method == 'POST': 
    result = request.form 
    return render_template("result.html",result = result) 

我們爲什麼要編寫結果=結果通過輸入render_template(時)?它看起來更笨重,當你可以把

return render_template("result.html", result) 

是否有一個原因,爲什麼Flask提出這樣的方法呢?

+0

除非您將該變量作爲關鍵字arg傳遞,否則該模板如何知道變量被調用? – davidism

回答

1

這背後的原因是您的模板文件可以有很多佔位符,它需要知道如何區分所有這些佔位符。

例如,你可以有下面的模板:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <title> {{ page_title }} 
</head> 
<body> 
    {{ page_body }} 
</body> 
</html> 

現在想想,你會不會有變量的名字,請問是需要呈現的頁面和注入的變量而不是函數的佔位符會知道在哪裏放置每個變量?這就是爲什麼你實際上以key=value的形式傳遞字典,並且可以將多個鍵和值傳遞給該函數,而不會限制函數知道期望的參數數量。

在上述例子中,該呼叫到render_template功能將是:

render_template('page.html', page_title='this is my title', page_body='this is my body') 

這是函數的實際簽名(從here截取):

def render_template(template_name_or_list, **context): 
    """Renders a template from the template folder with the given 
    context. 
    :param template_name_or_list: the name of the template to be 
            rendered, or an iterable with template names 
            the first one existing will be rendered 
    :param context: the variables that should be available in the 
        context of the template. 
    """ 

**context是Python的方式來聚合傳遞給函數的所有參數key=value,並將它們作爲字典形式使用:

{'key1': value1, 'key2': value2, ...} 

而且我猜想函數本身或被調用的子函數正在解釋模板頁面,並尋找模板中提供的變量名稱,其中的變量名稱與變量名稱相對應。

長話短說,這種方式的功能是足夠通用的,每個人都可以傳遞儘可能多的參數,並且該功能能夠正確呈現模板頁面。

相關問題