Attribute name with a dash character using helpers

174 views
Skip to first unread message

Jeff Plata

unread,
Jul 27, 2023, 1:46:24 AM7/27/23
to web2py-users
How do we achieve this using the BUTTON() helper

<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown">

I am having trouble with the "data-toggle" attribute.

Clemens

unread,
Jul 27, 2023, 4:07:32 AM7/27/23
to web2py-users
c.f. http://www.web2py.com/books/default/chapter/29/05/the-views#HTML-helpers

Notice that helper attributes are passed as keyword arguments to the helper. In some cases, however, attribute names include special characters that are not allowed in Python identifiers (e.g., hyphens) and therefore cannot be used as keyword argument names. For example:

DIV('text', _data-role='collapsible')

will not work because "_data-role" includes a hyphen, which will produce a Python syntax error.

In such cases you have a couple of options. You can use the data argument (this time without a leading underscore) to pass a dictionary of related attributes without their leading hyphen, and the output will have the desired combinations e.g.

>>> print DIV('text', data={'role': 'collapsible'})
<div data-role="collapsible">text</div>

or you can instead pass the attributes as a dictionary and make use of Python's ** function arguments notation, which maps a dictionary of (key:value) pairs into a set of keyword arguments:

>>> print DIV('text', **{'_data-role': 'collapsible'})
<div data-role="collapsible">text</div>

Regards
Clemens
Reply all
Reply to author
Forward
0 new messages