2014-03-14 42 views

回答

5

瓶內置的模板引擎支持inline if statements:在selected="selected"

<option value="{{make}}" {{!'selected="selected"' if make == defaults['make'] else ""}}>{{make}}</option> 

注意感嘆號 - 它告訴模板引擎沒有逃脫引號。

演示:

from bottle import SimpleTemplate 

tpl = SimpleTemplate("""Make = <SELECT name="where_make"> 
     % for make in makes: 
      <option value="{{make}}" {{!'selected="selected"' if make == defaults['make'] else ""}}>{{make}}</option> 
     %end""") 
print tpl.render(make='test', defaults={'make': 'test'}, makes=['test']) 

打印:

Make = <SELECT name="where_make"> 
      <option value="test" selected="selected">test</option> 

希望有所幫助。