pylons - pylon mako如何检查变量是否存在

标签 pylons mako

在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/

相关文章:

javascript - 有没有人有使用 Backbone.js 和 Pylons/Pyramid 的经验?有什么 sample 要看吗?

python - 虚拟环境中的 Pydev 和 Pylons,自动完成将不起作用

python - 我应该使用 Pylons 还是 Pyramid?

python - nosetests 和文件上传问题

python - .net automapper 有 python 实现吗?

javascript - 动态生成 jQuery 字段的 ID?

python - python如何返回Windows下当前正在处理的文件名

php - Mako 中使用 Pylons 的条件运算符

python - 如何检查mako dict中是否存在某个键?

jquery - CSS/jQuery - 悬停时图像上的文本