How can I use empy Templates with conditional expansion?

188 Views Asked by At

I try to use em.py's conditional to expand different, if a variable has a value:

import em

d1={"year":2012, "title":"abc"}
d2={"year":None, "title":"abc"}

p="@(year?year)@title" # the pattern
#p="@(year?year - )@title" # this does not work

print em.expand(p, d1)
print em.expand(p, d2)

# I would like to have it expanded into: "2012 - abc" for d1 and "abc" for d2

So, if the year is set (different from None), then the year should be inserted an a additional Separator (I use a dash with blanks around it: " - ") should also be inserted.

So: what pattern p should i use?

I am aware that this works:

@(year?year)@(year?" - ")

but that is not as readable as I like it to be.

1

There are 1 best solutions below

0
On BEST ANSWER

How about a python expression using and:

@(year and str(year) + ' - ')

If year is None, it short-circuits and returns None, otherwise it returns str(year) + ' - '. You need to use str(year) because otherwise you'd be concatenating an int and a str type.