Python 如何将empy模板与条件扩展一起使用?

Python 如何将empy模板与条件扩展一起使用?,python,templates,empy,Python,Templates,Empy,我尝试使用em.py的条件展开不同的变量,如果变量有值: 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 li

我尝试使用em.py的条件展开不同的变量,如果变量有值:

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
因此,如果设置了年份(不同于
None
),那么应该在年份中插入一个额外的分隔符(我使用一个带空格的破折号:“-”)

那么:我应该使用什么模式p?

我知道这是可行的:

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

但这并不像我希望的那样可读。

使用
的python表达式如何:

@(year and str(year) + ' - ')
如果
year
None
,则短路并返回
None
,否则返回
str(year)+'-'
。您需要使用
str(year)
,否则将连接
int
str
类型