On Fri, Apr 3, 2009 at 7:38 AM, KLEIN Stéphane <klein.steph...@gmail.com> wrote:
>
> Hi,
>
> What do you think about this web helper function ?
>
> ::
>
>    def tag_class(values):
>        values = [v for v in values if v != None]
>        if values:
>            return 'class="%s"' % " ".join(values)
>        return ''
>
> Example of use in mako template :
>
> ::
>
>    <tr>
>    % for i, column in enumerate(c.columns):
>        <th ${h.tag_class(("firstcolumn" if i == 0 else None, "asc" if
> request.GET.get("o") == "asc" else None))}>${column.name}</th>
>    % endfor
>    </tr>
>
> Thanks for your comment.
>
> Regards,
> Stephane

The first thing is to use the HTML object to create tags.  This
handles escaping in case the values contain markup characters, and is
the way all WebHelpers tags are built.

from webhelpers.html import HTML
print HTML.th(column.name, class_="firstcolumn asc")

This can be done in a template of course.

<%!  from webhelpers.html import HTML  %>
${HTML.th(column.name, class_="firstcolumn asc")}

This also means the function should return only the attribute value,
not the complete attribute.  I could go either way on that, since
programmable CSS classes are very common in applications.  I would
filter out all false values, not just None, because an empty string is
useless as a CSS class.  What one really wants is a list of
corresponding conditions and the value to choose if true.  I'm not
sure what's the best data structure for this.

def css_classes(value_condition_pairs):
    classes = []
    for value, condition in value_condition_pairs:
        if condition:    # Or ``if condition and value``
            classes.append(value)
    return " ".join(classes)

print css_classes([
    ("firstcolumn", i == 0),
    ("asc", request.get("o")),
    ]

How would that be?

I put the value first in the tuple to make the line more readable,
since it would be hard to ascertain after a complicated expression.

-- 
Mike Orr <sluggos...@gmail.com>

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"pylons-devel" group.
To post to this group, send email to pylons-devel@googlegroups.com
To unsubscribe from this group, send email to 
pylons-devel+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-devel?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to