[Zope] hasattr in tal:condition

Sylvain Thénault Sylvain.Thenault at logilab.fr
Mon Mar 15 16:50:01 EST 2004


On Monday 15 March à 11:41, Andre Meyer wrote:
> Dear Zopers
> 
> Is it the case that it is not possible to make use of hasattr within a 
> tal:condition statement? In a ZPT I need to test whether an attribute of 
> here/request is set or not. Unfortunately, this raises an exception, 
> which is exactly what I want to prevent...
>
> Here is what the test looks like:
> 
>    <span tal:condition="python:test(hasattr(request, results), 1, 
> 0)">span</span>

there is nothing preventing you to use hasattr in tal:condition. I think
your problem is that you haven't quoted the attribute name :

<span tal:condition="python:test(hasattr(request, 'results'), 1, 0)">span</span>
 
BTW, this is strictly equivalent to

<span tal:condition="python:hasattr(request, 'results')">span</span>

> Is there a better way to achieve the same?
> 
> thanks and regards
> Andre
> 
> PS in the full version the statement looks as follows:
> 
>    <body tal:define="results python:test(hasattr(request, results), 
> request.results, here.Catalog()); ... >

the problem here is that request.results is evaluated before the call to
test(), and so raises and attribute error (note also that the catalog
query is also executed whatever the result of the hasattr test). 
You can acheive the expected result using logical "and" and "or" :

 <body tal:define="results python:hasattr(request, 'results') and request.results or here.Catalog(); ... >

in this expression, request.results is evaluated only if
hasattr(request, 'results') is true and here.Catalog() only if it's
false.

-- 
Sylvain Thénault                               LOGILAB, Paris (France).

http://www.logilab.com   http://www.logilab.fr  http://www.logilab.org




More information about the Zope mailing list