Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 512
Fynn Avatar asked Nov 09 '10 18:11

Fynn


2 Answers

Genshi has a defined method for jut that

if defined(messages):

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

like image 178
Vince Spicer Avatar answered Oct 05 '22 12:10

Vince Spicer


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

like image 27
Jochen Ritzel Avatar answered Oct 05 '22 12:10

Jochen Ritzel