Skip to content

HTML5 Data Attributes for Pylons Webhelpers

HTML5 data attributes let developers store bits of meta-data directly within markup. They are an incredibly useful tool and I would highly recommend checking out the first few hits on Google for more details on exactly how they are used.

While working on BreakBase, I can across a bit of an issue with creating data attributes using Pylons’ Webhelper tags. Attributes are generally assigned in Webhelper tags using Python kwargs. This is an issue since data attributes require a dash character, which results in invalid Python code. Additionally, we use Mako templates so using an inline dict object is not an option since it will clash with the Mako delimiters.

Thus, I created a really simple helper that we can use in the meanwhile until data attribute support is added to Webhelpers directly. Here the helper method definition (and a github gist):

def data_attrs(**kwargs):
    attrs = {}
    for suffix in kwargs:
        key = "data-%s" % suffix
        attrs[key] = kwargs[suffix]
    return attrs

To use this helper, simply do the following:

${ h.link_to("link text", "/some/url", **h.data_attrs(some="data", available="here")) }

Which will produce the following valid markup:

<a href="/some/url" data-some="data" data-available="here">link text</a>