问题描述
我的目标是在HTML页面中动态编写一些图像的url。网址存储在数据库中。
My goal is to write dynamically some urls of images in the HTML page. Urls are stored in a database.
要这样做,首先我要在模板中渲染一个简单的变量。阅读文档和其他资源,应该分3个步骤完成:
To do so, first I am trying to render a simple varable in a template. Reading the docs and other sources, it should be done in 3 steps:
对于配置:在settings.py
TEMPLATES = [
{
'OPTIONS': {
'debug': DEBUG,
'context_processors': [
…
'django.template.context_processors.request',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages', ],
},
},
]
模板中的变量名称:在MyHTMLFile.html 中为foo
The variable name in the template: In MyHTMLFile.html is foo
…
<td>MyLabel</td><td><p>{{ foo }}</p></td><td>-----------</td>
…
view.py ,其中之一行
myvar1 ="BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
context = {foo: myvar1,}
return render_to_response("MyHTMLFile.html", context, context_instance = RequestContext(request) )
return render(request, 'MyHTMLFile.html', {foo: myvar1})
return render_to_response("MyHTMLFile.html", context , context_instance=RequestContext(request) )
return render(request, 'MyHTMLFile.html', context)
html页面呈现良好,但是html表中没有数据。
The html page is well rendered, but no data in the html table.
您有想法吗?
关于版本,我使用的是:
python:Python 2.7.13
django:1.10。 5
Regarding the versio, i am using:python: Python 2.7.13django: 1.10.5
谢谢
推荐答案
context = {foo: myvar1,}
这应该给您一个 NameError
除非您当然有一个名为 foo
的变量,在这种情况下它可能包含也可能不包含字符串 foo
。简而言之,您没有将正确的数据发送到模板。
This should give you a NameError
unless ofcourse you have a variable named foo
in which case it may or may not hold a string foo
. So in short you are not sending the right data to the template. It should be
context = {'foo': myvar1,}
然后
return render_to_response("MyHTMLFile.html", context, context_instance = RequestContext(request) )
# Below this line code will not be executed.
return render(request, 'MyHTMLFile.html', {foo: myvar1})
return render_to_response("MyHTMLFile.html", context , context_instance=RequestContext(request) )
return render(request, 'MyHTMLFile.html', context)
请注意,返回
关键字从该功能返回。
note that the return
keyword returns from the function. Code after that doesn't get executed.
最后,不推荐使用render_to_response。 render
是当前要使用的函数。
lastly render_to_response is deprecated. render
is the current function to use.
这篇关于如何在Django模板中呈现变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!