Check if a variable exists in tmpl_context (Python, Pylons, Genshi)?

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

I have a Pylons layout template. This should contain a message section if and only if the variable c.messagesexists in context. The message section is as follows:

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

This gives an error if the controller does not detect c.messages. Therefore, I would like to include this only if the variable is defined. Is there a solution to this problem?

+5
source share
3 answers

Genshi has a specific method for jut that

if defined (messages):

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

+4

hasattr(c, 'messages') and len(c.messages) > 0.. []

+3

I appreciate that I dig an old stream, but have an alternative solution.

I always tried to determine () to work correctly. The most effective solution I found is to use the following list:

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

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

0
source

All Articles