Django中的上下文渲染 [英] Context Rendering in Django

查看:39
本文介绍了Django中的上下文渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是django的新手.因此,当我在shell中练习django模板时,我看到了"render()"的两个不同输出.从django.template导入

I am new in django.So while i was practising django template in shell i saw two different output of "render()" .So here it goes.

from django.template import Template,Context
t = Template("My name is {{name}}.")
c = Context("name":"sraban")
t.render(c)

所以当我在shell中按Enter键时,它会显示

So while i hit enter in shell it shows

u'My name is sraban'

但是我写

from django.template import Template,Context
t = Template("My name is {{name}}.")
c = Context("name":"sraban")
print t.render(c)

它的输出是

My name is sraban

所以我想知道第一个输出中的多余"u"是什么,以及为什么两个输出不同???我在python 2.7.3中使用django1.6.

So I want to know what is that extra "u" in the first output and why two output varies??? I use django1.6 in python 2.7.3 .

推荐答案

补充克鲁罗克答案:

如果仔细看,您会发现 u 不是唯一的区别,在第二个输出中没有'字符.

If you take a look closer you will notice that the u is not the unique difference, in the second output there is no ' characters.

差异与使用两个不同的功能有关: repr str (如kroolik所指出的),您可以在此处阅读有关它们的信息:href ="https://docs.python.org/2/tutorial/inputoutput.html" rel ="nofollow">输入和输出

The difference has to do with the use of two different functions: repr and str-- as kroolik pointed out-- you can read about them here: Input and Output

取自Python文档.

Taken from Python Doc.

str()函数旨在返回相当容易理解的值表示形式,而 repr()则旨在生成表示形式,可以由解释程序读取(如果没有等效语法,则将强制产生SyntaxError).对于没有特定代表人类消费的对象,str()将返回与repr()相同的值.

The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is no equivalent syntax). For objects which don’t have a particular representation for human consumption, str() will return the same value as repr().

因此,这就是为什么您看到'u'的原因,解释器需要知道字符串是否为unicode,这就是它的处理方式.

So, that's why you see the 'u' the interpreter needs to know if a string is unicode or not and thats the way it does it.

在这一点上,您必须避免使用以下函数: Template.render 使用 repr()函数,而 print 不使用t.

At this point it must be obviuos to you that the function: Template.render use the repr() function while print doesn't.

这篇关于Django中的上下文渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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