Question

I am trying to figure out how to check if a variable exists in the template context 'tmpl_context' using Pylons and Python. What I am trying to do is:

I've got a Pylons layout template. This should contain a message section if, and only if, the variable c.messages exists in the context. The message section looks like this:

<div py:if="len(c.messages) > 0">
  <py:for each="msg in c.messages">
    <strong>${msg}</strong>
  </py:for>
</div>

This yields an error if the controller does not define c.messages. So I'd like to include this only if the variable is defined. Is there a solution for this problem?

Was it helpful?

Solution

Genshi has a defined method for jut that

if defined(messages):

http://genshi.edgewall.org/wiki/Documentation/templates.html#defined-name

OTHER TIPS

Turn the test into hasattr(c, 'messages') and len(c.messages) > 0 .. or simply set messages to [] by default

I appreciate I'm digging up an old thread, but have an alternative solution.

I've always struggled getting defined() to work properly. The most effective solution I've found is to use the following for a list:

py:if="myobject.thelist.get('blah',0) == 0"

Basic Python in Genshi - if it's undefined, we give it a default value. If you need to make sure the default value will not contaminate your data, return something else other than 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top