我希望Flask的“SubmitField”能够使用
<button type="submit" title="Save this form"><span>Save</span></button>
而不是:
<input type="submit" title="Save this form" />
我正在模板中打印出来:
{{ field(class=css_class, title=field.description, **kwargs) }}
我猜我必须以某种方式修改SubmitInput(SubmitField背后的小部件),但我不确定如何做到这一点,我是否必须修改__html __()?
修改
from flask.ext.wtf import Required, Length, EqualTo, Field, TextInput
from flask import Markup
class InlineButtonWidget(object):
html = """
<button type="submit" title="%s"><span>%s</span></button>
"""
def __init__(self, input_type='submit'):
self.input_type = input_type
def __call__(self, field, **kwargs):
kwargs.setdefault('id', field.id)
kwargs.setdefault('type', self.input_type)
if 'value' not in kwargs:
kwargs['value'] = field._value()
return HTMLString(self.html % (field.name, field.label ))
class InlineButton(Field):
widget = InlineButtonWidget()
def _value(self):
if self.data:
return u', '.join(self.data)
else:
return u''
class SignupForm(Form):
name = TextField('Name', [Length(min=1, max=200)])
submit = InlineButton('sign up')
我希望能够这样做:
submit = InlineButton({'name':'submit','title':'今天注册奖品。','type':'submitfieldtype','textInsideSpan':'保存当前工作'} )
答案 0 :(得分:5)
很简单,你可以像InlineButtonWidget()一样创建新的小部件,但我认为最好从表单中删除提交并在模板中使用它
<button type="submit" title="Save this form"><span>Save</span></button>
of cource你也可以使用它:
{% for name, label in buttons %}
<button type="submit" title="{{name}}"><span>{{name}}</span></button>
{% endfor %}
示例小部件:
class InlineButtonWidget(object):
html = """
<button type="submit" title="%s"><span>%s</span></button>
"""
def __init__(self, input_type='submit'):
self.input_type = input_type
def __call__(self, field, **kwargs):
kwargs.setdefault('id', field.id)
kwargs.setdefault('type', self.input_type)
if 'value' not in kwargs:
kwargs['value'] = field._value()
return HTMLString(self.html % (field.name, field.lable ))
答案 1 :(得分:0)
以下实施更通用。
from wtforms.widgets.core import html_params
from wtforms.widgets import HTMLString
class InlineButtonWidget(object):
"""
Render a basic ``<button>`` field.
"""
input_type = 'submit'
html_params = staticmethod(html_params)
def __call__(self, field, **kwargs):
kwargs.setdefault('id', field.id)
kwargs.setdefault('type', self.input_type)
kwargs.setdefault('value', field.label.text)
return HTMLString('<button %s>' % self.html_params(name=field.name, **kwargs))
class InlineSubmitField(BooleanField):
"""
Represents an ``<button type="submit">``. This allows checking if a given
submit button has been pressed.
"""
widget = InlineButtonWidget()
class SignupForm(Form):
name = TextField('Name', [Length(min=1, max=200)])
submit = InlineSubmitField('sign up')