How to put random attributes in A()?

71 views
Skip to first unread message

pbreit

unread,
Apr 23, 2012, 12:09:28 AM4/23/12
to web...@googlegroups.com
How can I make this <a> tag with A()?

<a class="btn" data-toggle="modal" href="#myModal" >Launch Modal</a>

Jonathan Lundell

unread,
Apr 23, 2012, 12:23:50 AM4/23/12
to web...@googlegroups.com
On Apr 22, 2012, at 9:09 PM, pbreit wrote:
How can I make this <a> tag with A()?

<a class="btn" data-toggle="modal" href="#myModal" >Launch Modal</a>

I'd try something like A('Launch Modal', **{ '_class' : 'btn', '_data-toggle' : 'modal', '_href' : '#myModal'})


Anthony

unread,
Apr 23, 2012, 12:30:33 AM4/23/12
to web...@googlegroups.com
This keeps coming up. Note, it's actually in the book: http://web2py.com/books/default/chapter/29/5#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:

1.
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:

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

Jonathan Lundell

unread,
Apr 23, 2012, 12:41:45 AM4/23/12
to web...@googlegroups.com
On Apr 22, 2012, at 9:30 PM, Anthony wrote:
> This keeps coming up. Note, it's actually in the book: http://web2py.com/books/default/chapter/29/5#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>

It's worth noting that this is all (aside from web2py's underscore convention for passing attributes) straightforward Python.

Reply all
Reply to author
Forward
0 new messages