简体   繁体   English

在 flask-wtforms 中自动设置表单元素的 id HTML 属性

[英]Automatically setting the id HTML attribute of a form element in flask-wtforms

Is there a way to automatically have the id of a form input element itself to the name of the form and the name of the field variable?有没有办法自动将表单输入元素本身的id设置为表单名称字段变量的名称? ie for a bar field in a FooForm instance, the id would be foo-form--bar .即对于FooForm实例中的bar字段, id将是foo-form--bar

I am currently using this approach to achieve this, but it's a bit cumbersome:我目前正在使用这种方法来实现这一点,但这有点麻烦:

from flask_wtf import FlaskForm
import wtforms as wtf

class FooForm(FlaskForm):
    FORM_NAME = 'foo-form'
    bar =  wtf.StringField('Bar', render_kw={'id': f'{FORM_NAME}--bar'})

I think subclassing complicates this, since the subclass contains only one or two lines.我认为子类化使这个复杂化,因为子类只包含一两行。 You can do the following:您可以执行以下操作:

def class_id(s):
    """Convert input string from PascalCase to kebab-case"""
    import re
    return re.sub(r'(?<!^)(?=[A-Z])', '-', s).lower() + '-'

class MyClass(object):
    form_name = class_id(__qualname__)
    print(f"{form_name}attribute")

class OtherClass(object):
    form_name = class_id(__qualname__)
    print(f"{form_name}attribute")

>>> MyClass()
>>> OtherClass()
my-class-attribute
other-class-attribute

edit: sorry completely missed the part about the id being automatic, then subclassing would be necessary, a simple approach would be:编辑:抱歉完全错过了关于id是自动的部分,那么子类化是必要的,一个简单的方法是:

def AdjStringField(form_name, **kwargs):
    name = kwargs.get('name', 'Bar')
    return wtf.StringField(name, render_kw={
        'id': f'{}{}'.format(form_name, name.lower(),
        **kwargs.get('render_kw', {})})

class FooForm(FlaskForm):
    form_name = class_id(__qualname__)
    bar = AdjStringField(form_name)
    pipe = AdjStringField(form_name, name='Pipe', render_kw={'foo': 'bar'})

You can overload this for any input field type provided you supplied it as in argument object:只要您在参数 object 中提供它,您就可以为任何输入字段类型重载它:

def AdjField(Field, form_name, **kwargs):
    name = kwargs.get('name', 'Bar')
    return Field(name, render_kw={
        'id': f'{}{}'.format(form_name, name.lower(),
        **kwargs.get('render_kw', {})})

>>> AdjField(wtf.StringField, 'form-name')
>>> AdjField(wtf.InputBox, 'other-name', name='Pipe', render_kw={'foo': 'bar'})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM