将变量从python(烧瓶)传递到渲染模板中的HTML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45149420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:46:02  来源:igfitidea点击:

Pass Variable from python (flask) to HTML in render template?

pythonhtmlparsingvariablesflask

提问by ThePGT

The web server works (python flask) but when I go to the website, where the value of animal should be (dog) it shows the variable name animal. (There is more to the code but this is the most simplistic version which is the same concept.

Web服务器工作(python烧瓶)但是当我访问网站时,animal的值应该是(dog)它显示了变量名animal。(代码还有更多,但这是同一个概念的最简单版本。

Let's say I have these lines of code in my python script running python flask.

假设我在运行 python flask 的 python 脚本中有这些代码行。

animal = dog
return render_template('index.html', value=animal)

and in my HTML

在我的 HTML 中

<h3>I like the animal: {{ value }}<h3>

but rather than displaying 'dog' it displays the variable name 'animal'. So how would I go about displaying the Python variable to HTML? Thank you

但不是显示“狗”,而是显示变量名称“动物”。那么我将如何将 Python 变量显示为 HTML?谢谢

回答by Renato Byrro

Shouldn't it be animal = 'dog'? If 'dog' is the value you want to see printed after "I like the animal:", this is what you need to do:

不应该animal = 'dog'吗?如果 'dog' 是你想在“I like the Animal:”之后看到的值,这就是你需要做的:

animal = 'dog'
return render_template('index.html', value=animal)

回答by Ashutosh Sharma

As you have to pass a value using a variable you have to define it as a string like: animal = 'dog'then pass it to the html template: return render_template('index.html', value=animal)

由于您必须使用变量传递值,因此您必须将其定义为字符串,例如: animal = 'dog'然后将其传递给 html 模板: return render_template('index.html', value=animal)

Now, you should see the passed value in the HTML.

现在,您应该会在 HTML 中看到传递的值。