Pylons mako how to check if a variable exists or not

In django we can do this:

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 %}

And our rendering of the template is error-free, even if I use method Bit where the variable 'test'does not exist, but I can still put it in the template.

I want to do the same with pylons + mako, in the controller:

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

In Django I can do this, but in Pylons I get an error message, is there a way to check if exter exists 'c.test'or not?

error: AttributeError: object 'ContextObj' does not have attribute 'test'

+5
source share
3 answers

From mako docs for 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 NameError. , , , Python. , , , Mako Runtime, , , .

Edit:
strict_undefined . , .ini:

[app:main]
...
mako.strict_undefined = false
+4

, , ​​. docs chris , mako.strict_undefined. get() context. :

% if context.get('test', UNDEFINED) is not UNDEFINED:
  ${test}
% endif

${context.get('test', '')}

, ${test}, , , .

, in context, .

+6

a little late, so whenever you use a variable on your template that does not exist on your controller, the pylons will raise an error to disable this error, just put this in your environment.py:

config['pylons.strict_tmpl_context'] = False
0
source

All Articles