我有一个非常基本的问题(我第一次使用Flask,我不习惯web框架)。
我只想更新模板中的变量,例如hello.html,没有其他东西(我现在不关心路由或其他任何东西)
我是根据一篇教程这样做的:
from flask import Flask, render_template
app = Flask(__name__)
x=1986
res=render_template('hello.html', myVar = x)
print(res)
if __name__ == '__main__':
app.run(debug = True)请注意,我在一个名为templates的子目录中有一个名为hello.html的html文件。hello.html:
<!doctype html>
<html>
<body>
<h1>Hello {% print(myVar) %}</h1>
</body>
</html>我做错了什么?
编辑。我收到这个错误消息:
Traceback (most recent call last):
File "flask_test1.py", line 7, in <module>
res=render_template('hello.html', myVar = x)
File "/root/miniconda3/lib/python3.4/site-packages/flask/templating.py", line 133, in render_template
ctx.app.update_template_context(context)
AttributeError: 'NoneType' object has no attribute 'app'附注:很抱歉我在web框架上的“笨拙”。
发布于 2018-08-07 00:03:27
你的代码结构是不可能工作的。flask中的基本概念是上下文。通常,您可以认为这是单个请求的完整作用域。
因此,正如您在错误消息中看到的,上下文是None。您不能像这样使用render_template。
相反,您可以直接使用flask使用的底层呈现引擎:jinja2。
from jinja2 import Environment, FileSystemLoader, select_autoescape
env = Environment(
loader=FileSystemLoader('your/templates/dir'),
autoescape=select_autoescape(['html', 'xml'])
)
template = env.get_template('hello.html')
x = 1986
print(template.render(myVar = x))你的模板应该是:
<!doctype html>
<html>
<body>
<h1>Hello {{ myVar }}</h1>
</body>
</html>发布于 2018-08-06 23:51:48
你没有说你正在遵循的是什么教程,但我很确定它没有显示出这种结构。
您需要将代码放在一个函数中,并使用要使用的URL对其进行修饰;然后,您需要从函数返回呈现的模板,而不是打印它。
@app.route("/")
def index():
x = 1986
res = render_template('hello.html', myVar=x)
return res此外,您不能在模板中使用print();要输出变量的值,请使用{{ }}而不是{% %}。
<h1>Hello {{ myVar }}</h1>https://stackoverflow.com/questions/51711374
复制相似问题