在WTForms中使用自定义属性创建selectfield选项 [英] Create selectfield options with custom attributes in WTForms
问题描述
我正在尝试创建一个 SelectField
或 SelectMultipleField
,以允许向其< option>
标记添加属性.我正在尝试添加 data-id
或其他 data -____
之类的属性.我一直无法弄清楚该怎么做,因为似乎只能将属性添加到< select>
标记本身而不是选项中.
最终结果应该类似于:
I am trying to create a SelectField
or SelectMultipleField
that allows me to add attributes to it's <option>
tags. I am trying to add attributes like data-id
or another data-____
. I have not been able to figure out how to do this as it only seems possible to add attributes to the <select>
tag itself and not the options.
The end result should be something like:
<select id="regularstuff-here" name="regular-name-here">
<option value="1" data-id="somedata here" >Some Name here</option>
<option value="2" data-id="somedata here" >Some Name here</option>
</select>
我假设我必须创建一个自定义窗口小部件.如果查看WTForms的来源,我会看到 select
小部件调用:
I assume I have to create a custom widget. If I look at the source for WTForms I see that select
widget calls:
html.append(self.render_option(val, label, selected))
如果我看这种方法:
@classmethod
def render_option(cls, value, label, selected, **kwargs):
options = dict(kwargs, value=value)
if selected:
options['selected'] = True
return HTMLString('<option %s>%s</option>' % (html_params(**options),
escape(text_type(label))))
因此,您似乎无法将任何额外的参数传递给呈现 option
标记的方法.
So it does not seem that you can pass any extra params to the method that renders the option
tags.
推荐答案
我只是想说,没有猴子补丁或重写wtforms,这是可能的.库代码确实支持它,尽管不是很直接.我找到了这个原因是因为我试图为WTForms编写修复程序,然后自己提交了PR,然后发现您可以做到这一点(我花了很多天试图弄清楚这一点):
I just wanted to say that this is possible without monkey patching or rewriting wtforms. The library code does support it although not very straightforwardly. I found this out because I attempted to write a fix for WTForms and submitted a PR myself and found out afterwards that you can just do this (I've spent days trying to figure this out):
>>> from wtforms import SelectField, Form
>>> class F(Form):
... a = SelectField(choices=[('a', 'Apple'), ('b', 'Banana')])
...
>>> i = 44
>>> form = F()
>>> for subchoice in form.a:
... print subchoice(**{'data-id': i})
... i += 1
...
<option data-id="44" value="a">Apple</option>
<option data-id="45" value="b">Banana</option>
在此处查看convo:
https://github.com/wtforms/wtforms/pull/81
See the convo here:
https://github.com/wtforms/wtforms/pull/81
这篇关于在WTForms中使用自定义属性创建selectfield选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!