我正在尝试传递“Hello World!”从 Django View 到 index.html
view.py(请原谅简洁):
def index(request):
context = "Hello World!"
return render(request, 'hud/index.html', {"context": context})
index.html(简洁):
<html>
<h1>{{ index.context }}</h1>
</html>
我期望它打印“context”的值,但它没有。我没有收到任何错误,只是出现空白屏幕。在 chrome 页面源代码中,我看到:
<html>
<h1></h1>
</html>
感谢任何帮助,我是新人!
最佳答案
你可以这样尝试吗?
在Python中:
def index(request):
context = "Temp = {0} *C".format(sensor.read_temperature)
return render(request, 'hud/index.html', {"context": context})
在模板中:
<h1>{{ context }}</h1>
你应该发送带有字典的变量 {"context": context} 是我们的字典。在Django模板中,数据是通过key传递的,所以我们可以通过{{ context }}来获取它。您必须传递一个对象才能使用 doted (index.context) 语法来获取。
关于python - Django View 变量未在 html 中显示任何数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29955783/