hasattr in tal:condition
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> 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()); ... >
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
Andre Meyer wrote:
<span tal:condition="python:test(hasattr(request, results), 1, 0)">span</span>
using hasattr in any Zope-ish python is BAD, since it ignores all exceptions, including things like ConflictErrors, which you NEVER want to catch...
PS in the full version the statement looks as follows:
<body tal:define="results python:test(hasattr(request, results), request.results, here.Catalog()); ... >
<body tal:define="results getattr(request,'results',here.Catalog()); ... > cheers, Chris -- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk
participants (3)
-
Andre Meyer -
Chris Withers -
Sylvain Thénault