Skip to content

Instantly share code, notes, and snippets.

@elmcrest
Created August 13, 2013 17:11
Show Gist options
  • Save elmcrest/6223352 to your computer and use it in GitHub Desktop.
Save elmcrest/6223352 to your computer and use it in GitHub Desktop.
import sys
if sys.version_info[0] >= 3:
text_type = str
string_types = str,
iteritems = lambda o: o.items()
itervalues = lambda o: o.values()
izip = zip
else:
text_type = unicode
string_types = basestring,
iteritems = lambda o: o.iteritems()
itervalues = lambda o: o.itervalues()
from itertools import izip
def with_metaclass(meta, base=object):
return meta("NewBase", (base,), {})
from wtforms.compat import text_type, string_types, iteritems
def html_params(**kwargs):
"""
Generate HTML parameters from inputted keyword arguments.
The output value is sorted by the passed keys, to provide consistent output
each time this function is called with the same parameters. Because of the
frequent use of the normally reserved keywords `class` and `for`, suffixing
these with an underscore will allow them to be used.
>>> html_params(name='text1', id='f', class_='text') == 'class="text" id="f" name="text1"'
True
"""
params = []
for k,v in sorted(iteritems(kwargs)):
if k in ('class_', 'class__', 'for_'):
k = k[:-1]
if v is True:
params.append(k)
else:
params.append('%s="%s"' % (text_type(k), escape(text_type(v), quote=True)))
return ' '.join(params)
class HTMLString(text_type):
def __html__(self):
return self
class Input(object):
"""
Render a basic ``<input>`` field.
This is used as the basis for most of the other input fields.
By default, the `_value()` method will be called upon the associated field
to provide the ``value=`` HTML attribute.
"""
html_params = staticmethod(html_params)
def __init__(self, input_type=None):
if input_type is not None:
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('<input %s>' % self.html_params(name=field.name, **kwargs))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment