2016-10-25 58 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>