2016-10-25 102 views
0

我想解析一個使用美麗的湯的本地HTML文檔,然後render_template()結果使用jinja2。解析使用jinja2中美麗的湯&呈現模板的HTML

我是新來的蟒蛇,但在這裏就是我想:

@app.route("inherit/index") 
def inheritIndex(): 
    soup = BeautifulSoup(open("templates/index.html"), "html.parser") 
    soup.find(text="foobar").replaceWith("Hooray!") 
    return render_template(soup) 
+1

什麼是問題? BTW。 'render_template'預計文件名不是BS對象。也許你需要[render_template_string()](http://flask.pocoo.org/docs/0.11/api/#flask.render_template_string) – furas

+0

我的問題是試圖渲染一個jinja2模板的東西已被解析使用BS。感謝您的建議,但它沒有幫助。 – whatevermike

+1

BS可以將結果作爲HTML字符串,並且可以將其保存在文件中以與render_template(filename)一起使用,或嘗試直接使用此HTML字符串與'render_template_string(html_string)' – furas

回答

1

我設法從render_template()方法中權替代值。 BeautifulSoup不是必需的。這是我在評論中提出的解決方案。

HTML:

... 
<p> {{ foobar }} lorem ipsum dolor...</p> 
... 

的Python:

@app.route("inherit/index") 
    def inheritIndex(): 
    return render_template("index.html", foobar="Hooray!") 

    # <p> Hooray! lorem ipsum dolor...</p>