如何在 Django 模板中呈现变量? [英] How to render a variable in a django template?

查看:48
本文介绍了如何在 Django 模板中呈现变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是在 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.

你有什么想法吗?我很想知道我误解了什么.

Do you have an idea ? I am curious to know what i misunderstand.

关于版本,我正在使用:蟒蛇:Python 2.7.13Django: 1.10.5

Regarding the versio, i am using: python: Python 2.7.13 django: 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)

注意 return 关键字 returns 从函数中.之后的代码不会被执行.

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 模板中呈现变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆