在django中,我们可以执行以下操作:
views.py :
def A(request):
context = {test : 'test'}
return render_to_response('index.html', context , context_instance = RequestContext(request))
def B(request):
context = {}
return render_to_response('index.html', context , context_instance = RequestContext(request))
index.html:
{% if test %}
{{ test }}
{% endif %}
即使我使用
method B
(不存在变量'test'
,但我仍然可以将其放入模板)中,也可以使我们的模板呈现没有错误。我想在 Controller 中使用pylon + mako做同样的事情:
foo.py
def A(self):
c.test = 'test'
return render('index.html')
def B(self):
return render('index.html')
index.html :
% if c.test:
${'c.test'}
% endif
在Django中,我可以这样做,但是在Pylons中,我得到一个错误,是否仍然需要检查
'c.test'
是否存在?错误:AttributeError:'ContextObj'对象没有属性'test'
最佳答案
从mako Docs on Context Variables:
% if someval is UNDEFINED:
someval is: no value
% else:
someval is: ${someval}
% endif
文档将其描述为,它引用的变量名称不在当前上下文中。 Mako会将这些变量设置为
UNDEFINED
值。我检查像这样的变量:
% if not someval is UNDEFINED:
(safe to use someval)
但是,如果pylons/pyramid具有
strict_undefined=True
设置,则尝试使用 undefined variable 会导致NameError
升高。他们以这种方式给出了简要的哲学依据,而不是简单地用空字符串替换未设置的变量,这似乎与Python原理一致。花了我一段时间才能找到答案,但是阅读整个section on the Mako Runtime将会弄清楚Mako如何接收,设置和使用上下文变量。编辑:
为了完整起见,文档解释了
strict_undefined
设置here。您可以通过在一个.ini文件中进行设置来更改此变量:[app:main]
...
mako.strict_undefined = false
关于pylons - pylon mako如何检查变量是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12006720/