Source

thelayouts / thelayouts / utils.py

# -*- coding: utf-8 -*-

import cgi
import os


__all__ = (
    'escape', 'html_params', 'HTMLString',
)


def escape(s, quote=None):
    if hasattr(s, '__html__'):
        return s
    return cgi.escape(unicode(s), quote=quote)


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', 'short'], value=None)
    u' class="text short" id="f" name="text1"'
    """
    params = {}
    attrs = []
    for k, v in sorted(kwargs.iteritems()):
        if v is None:
            continue
        if k.endswith('_'):
            k = k[:-1]
        if isinstance(v, (list, tuple)):
            params.setdefault(k, []).extend(v)
        else:
            params.setdefault(k, []).append(v)
    for k, v in sorted(params.iteritems()):
        attrs.append(HTMLString(
            u'%s="%s"' % (
                unicode(k), 
                u' '.join([escape(w, quote=True) for w in v]),
            )
        ))
    if attrs:
        return HTMLString(u' %s' % u' '.join(attrs))
    return u''


class HTMLString(unicode):
    def __html__(self):
        return self
    
    def __add__(self, rhs):
        t = super(HTMLString, self).__add__(rhs)
        if hasattr(rhs, '__html__'):
            return HTMLString(t)
        return t