Is there any convenient/standard way to generate html select menu using list variable?
For example I have list variable elements=['aaa','zzz','sss']
And need to generate drop down select menu using this variable:
<select name="dropdown" >
<option value="aaa">aaa</option>
<option value="zzz"> zzz </option>
<option value="sss"> sss </option>
</select> <br />
In Perl for example I can use CGI module and just specify :
popup_menu(-name=>'dropdown', -values=>['NULL',@elements])
Thank you in advance
-
Maybe this would work stackoverflow.com/questions/1548474/python-html-generatorJohn Giotta– John Giotta2010年12月28日 14:57:55 +00:00Commented Dec 28, 2010 at 14:57
-
Lots of suggestions from this as well: stackoverflow.com/questions/521621/… It's mostly is suggestions for template engines, but it sounds like Genshi has a direct HTML generator.mjhm– mjhm2010年12月28日 15:06:05 +00:00Commented Dec 28, 2010 at 15:06
3 Answers 3
def makeSelect(name,values):
SEL = '<select name="{0}">\n{1}</select>\n'
OPT = '<option value="{0}">{0}</option>\n'
return SEL.format(name, ''.join(OPT.format(v) for v in values))
answered Dec 29, 2010 at 2:52
Hugh Bothwell
57k9 gold badges91 silver badges103 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Ruslan
Simple and efficient. Thank you, exactly what I need.
Hugh Bothwell
Glad to help. Please feel free to tag it as the solution! ;-)
I'm not aware of a native markup generator, but this library looks promising.
EDIT: It looks like it hasn't been worked on since 2007
answered Dec 28, 2010 at 14:55
John Giotta
17.1k7 gold badges55 silver badges83 bronze badges
Comments
Expanding Hugh's answer a bit, someone might need a selected option:
def makeSelect(name, values, selectedValue=None):
SEL = '<select name="{0}">\n{1}</select>\n'
OPT = '<option value="{0}"{1}>{0}</option>\n'
return SEL.format(name, ''.join(OPT.format(v, " SELECTED" if v==selectedValue else "") for v in values))
Comments
default