[ZPT] Re: TAL's lack of an else...

Charlie Clark charlie at begeistert.org
Wed Aug 6 12:54:11 EDT 2003


On 2003-08-04 at 12:30:39 [+0200], Fergal Daly wrote:
> if user.isLoggedIn:
>   print "You are logged in"
> elif user.hasCookie:
>   print "Welcome back please log in"
> else
>   print "Please register"
> 
> you had to write
> 
> isLoggedIn = user.isLoggedIn
> if isLoggedIn:
>   print "You are logged in"
> if not isLoggedIn:
>   hasCookie = user.hasCookie
>   if hasCookie:
>     print "Welcome back please log in"
>   if not hasCookie:
>     print "Please register"
> 
> I doubt you would be happy with that. So why are people happy with it in 
> TAL? It would be undestandable if it was an uncommon construct but it's 
> not, it's very common and the whole purpose of a good language is to make 
> the very common as easy as possible.

Au contraire, I think we could live with that because we don't need it 
anyway: we can use dictionary based dispatching for this kind of work. This 
reduces the amount of hard-coded if/elif/else making the code more flexible 
and more easy to maintain.

cases = {isLoggenIn : "You are logged in"}

try:
	print cases[isLoggedIn]
except:
	print "You are not logged in"

Slightly synthetic example which might not actually work here. I refer to 
the Python Cookbook for more examples and explanations. The important thing 
I've learned from this is that is gives me more control over the logic. 
Another important point: you need to know Python to get the most out of 
Zope.

Regarding TALES-extension: I've come to understand and appreciate TALES for 
as an essentially declarative language which is appropriate for 
presentation. Conditions are usually binary in nature and should be kept to 
a minimum in templates for manageability. if/elif/else allows us to build 
chains of procedural logic whereas conditions only execute if met and are, 
thus, essentially purely declarative; it's important to understand this 
distinction, I think.

Context-based presentation seems to me the most likely case for non-binary 
conditionals: a user might be a visitor, an editor or a publisher, for 
example. Filling a template full of conditionals in this respect would seem 
to me the wrong way of doing things and likely to go wrong. I've currently 
got a site with various possible log-in types and I'm not happy that I can 
see all the possibilities in the master template at the same time.

Re. your actual itch: does it still need scratching? I've read some very 
good suggestions on dealing with the situations where if/elif/else might 
seem to be required.

Charlie



More information about the ZPT mailing list