对于下面的第一行,jinja2模板呈现x
是否存在。但是,在第二行中,模板仅在x
是现有列表时呈现。如果不是我收到错误(假设存在<p>x: {{ x }}</p>
<p>x[0]: {{ x[0] }}</p>
UndefinedError: 'x' is undefined
,则始终是包含至少一个项目的列表):
x
有没有更好的方法来检查一个变量是否存在并得到它的第一个项目而不是我在这里(我有大量的{% if x %}
<p>x[0]: {{ x[0] }}</p>
{% endif %
实例在我的模板中有更长的名称而我宁愿没有每次用if子句包装它:)
import web
from gothonweb import map
urls = (
'/game', 'GameEngine',
'/', 'Index',
)
app = web.application(urls, globals())
# little hack so that debug mode works with sessions
if web.config.get('_session') is None:
store = web.session.DiskStore('sessions')
session = web.session.Session(app, store,
initializer={'room': None})
web.config._session = session
else:
session = web.config._session
render = web.template.render('templates/', base="layout")
class Index(object):
def GET(self):
# this is used to "setup" the session with starting values
session.room = map.START
web.seeother("/game")
class GameEngine(object):
def GET(self):
if session.room:
return render.show_room(room=session.room)
else:
# why is there here? do you need it?
#this is to render death screen
# this is the none part of the get in the 'go' method
return render.you_died()
def POST(self):
form = web.input(action=None)
# there is a bug here, can you fix it?
if session.room and form.action:
session.room = session.room.go(form.action)
web.seeother("/game")
if __name__ == "__main__":
app.run()
答案 0 :(得分:1)
Jinja支持内联if else
语句,与Python不同,它也允许省略else
。
{{ x[0] if x }}
答案 1 :(得分:0)
也许尝试返回一个列表列表并迭代它,这样你只需要编写&#34;变量检查&#34;一旦。
这些方面的东西:
{% for x in list %}
{% if x %}
<p>x[0]: {{ x[0] }}</p>
{% endif %}
{% endfor %}