Search code examples
htmltemplate-talzpt

Storing data in HTML tags as custom attributes


Is it a good practice storing related information in the HTML tag?

$("#my_div").append("<span id='info' boo='foo'/>");
$("#info").attr("boo");

I've encountered with such technique (and slightly borrowed it) in TAL (in ZPT) where you could use tal:attributes statement to modify HTML tags (e.g. passing the value of boo variable from backend to be rendered in the final document as attribute value):

<span id='info' tal:attributes='boo view/boo'>

result:

<span id='info' boo='foo'>

Will this technique break a document someday, or it is safe by the spec?


Solution

  • The right way to do it is to use data-* attributes:

    http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes

    Tangentially, jQuery has a special method for working with these as well. For example:

    <p id='string' data-user_name='thedude'></p>
    $('#string').data('user_name') => "thedude"
    typeof $('#string').data('name') => "string"
    
    <p id='number' data-user_id='12345'</p>
    typeof $('#number').data('user_id') => "number"
    
    <p id='boolean' data-user_is_active='true'></p>
    typeof $('#boolean').data('user_is_active') => "boolean"
    
    <p id = 'json' data-user='{"name": "the dude", "id": "12345"}'></p>
    typeof $('#json').data('user') => "object"
    // embedding JSON is extremely useful in my experience