keyword can't be an expression

733 views
Skip to first unread message

Annet

unread,
Apr 4, 2013, 5:52:34 AM4/4/13
to web...@googlegroups.com
In a function I have the following code:


form.element('input[id=what3]').update(_data-content="My text", _data-toggle="popover", _title="", _data-original-title="My title")

This code cannot be saved, it result in a keyword can't be an expression error.
data-content, data-toggle and data-original-title are bootstrap attributes why can't I use them this way?



Annet

Anthony

unread,
Apr 4, 2013, 8:13:42 AM4/4/13
to web...@googlegroups.com
See the end of this section in the book: http://web2py.com/books/default/chapter/29/05#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 can instead pass the attributes as a dictionary and make use of Python's ** function arguments notation, which map a dictionary of (key:value) pairs into a set of keyword arguments:

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

And specifically for "data-*" attributes, you can now do:

form.element('input[id=what3]').update(
    data
={'content':'My text', 'toggle':'popover', 'original-title':'My title'}, _title='')

HTML helpers can now take a "data" argument, which is a dict -- the keys of the dict will be transformed into HTML attributes of the form "data-[key]".

Note, if the helper already has a "data" argument and you want to add more data-* attributes, you would update the "data" dict itself, as follows:

form.element('input[id=what3]')['data'].update(newattribute='newvalue')

Anthony

Annet

unread,
Apr 4, 2013, 10:14:09 AM4/4/13
to web...@googlegroups.com
Hi Anthony,

Thanks for the reference and for your extensive explanation how to solve my problem. The popover works!

Best regards,

Annet
Reply all
Reply to author
Forward
0 new messages