Exemplo n.º 1
0
 def test_boolean_true(self):
     a = {"defer": True, "disabled": "1", "multiple": 1, 
         "readonly": "readonly"}
     b = {"defer": "defer", "disabled": "disabled", "multiple": "multiple",
         "readonly": "readonly"}
     HTML.optimize_attrs(a)
     assert a == b
Exemplo n.º 2
0
def test_unclosed_tag():
    result = HTML.form(_closed=False)
    print result
    eq_(u'<form>', result)
    
    result = HTML.form(_closed=False, action="hello")
    eq_(u'<form action="hello">', result)
Exemplo n.º 3
0
 def test_boolean_true(self):
     a = {"defer": True, "disabled": "1", "multiple": 1, 
         "readonly": "readonly"}
     b = {"defer": "defer", "disabled": "disabled", "multiple": "multiple",
         "readonly": "readonly"}
     HTML.optimize_attrs(a)
     assert a == b
Exemplo n.º 4
0
    def table_totals(self, rownum, record, label, numrecords):
        row_hah = self.table_tr_styler(rownum, record)
        row_hah.class_ += 'totals'

        # get the <td>s for this row
        cells = []
        colspan = 0
        firstcol = True
        for col in self.grid.iter_columns('html'):
            if col.key not in list(self.grid.subtotal_cols.keys()):
                if firstcol:
                    colspan += 1
                else:
                    cells.append(_HTML.td(literal('&nbsp;')))
                continue
            if firstcol:
                bufferval = ngettext('{label} ({num} record):',
                                     '{label} ({num} records):',
                                     numrecords,
                                     label=label)
                buffer_hah = HTMLAttributes(
                    colspan=colspan,
                    class_='totals-label'
                )
                if colspan:
                    cells.append(_HTML.td(bufferval, **buffer_hah))
                firstcol = False
                colspan = 0
            cells.append(self.table_td(col, record))

        return self.table_tr_output(cells, row_hah)
Exemplo n.º 5
0
def form(url, method="post", multipart=False, hidden_fields=None, **attrs):
    """An open tag for a form that will submit to ``url``.

    You must close the form yourself by calling ``end_form()`` or outputting
    </form>.
    
    Options:

    ``method``
        The method to use when submitting the form, usually either 
        "GET" or "POST". If "PUT", "DELETE", or another verb is used, a
        hidden input with name _method is added to simulate the verb
        over POST.
    
    ``multipart``
        If set to True, the enctype is set to "multipart/form-data".
        You must set it to true when uploading files, or the browser will
        submit the filename rather than the file.

    ``hidden_fields``
        Additional hidden fields to add to the beginning of the form.  It may
        be a dict or an iterable of key-value tuples. This is implemented by
        calling the object's ``.items()`` method if it has one, or just
        iterating the object.  (This will successfuly get multiple values for
        the same key in WebOb MultiDict objects.)

    Because input tags must be placed in a block tag rather than directly
    inside the form, all hidden fields will be put in a 
    '<div style="display:none">'.  The style prevents the <div> from being
    displayed or affecting the layout.

    Changed in WebHelpers 1.0b2: add <div> and ``hidden_fields`` arg.

    Changed in WebHelpers 1.2: don't add an "id" attribute to hidden tags
    generated by this helper; they clash if there are multiple forms on the
    page.
    """
    fields = []
    attrs["action"] = url
    if multipart:
        attrs["enctype"] = "multipart/form-data"
    if method.lower() in ['post', 'get']:
        attrs['method'] = method
    else:
        attrs['method'] = "post"
        field = hidden("_method", method, id=None)
        fields.append(field)
    if hidden_fields is not None:
        try:
            it = hidden_fields.items()
        except AttributeError:
            it = hidden_fields
        for name, value in it:
            field = hidden(name, value, id=None)
            fields.append(field)
    if fields:
        div = HTML.tag("div", style="display:none", _nl=True, *fields)
    else:
        div = None
    return HTML.tag("form", div, _closed=False, **attrs)
Exemplo n.º 6
0
def radio(name, value, checked=False, label=None, **attrs):
    """Create a radio button.

    Arguments:
    ``name`` -- the field's name.

    ``value`` -- the value returned to the application if the button is
    pressed.

    ``checked`` -- true if the button should be initially pressed.

    ``label`` -- a text label to display to the right of the button.
    
    The id of the radio button will be set to the name + '_' + value to 
    ensure its uniqueness.  An ``id`` keyword arg overrides this.  (Note
    that this behavior is unique to the ``radio()`` helper.)
    
    To arrange multiple radio buttons in a group, see
    webhelpers2.containers.distribute().
    """
    _set_input_attrs(attrs, "radio", name, value)
    if checked:
        attrs["checked"] = "checked"
    if not "id" in attrs:
        attrs["id"] = '%s_%s' % (name, _make_safe_id_component(value))
    widget = HTML.input(**attrs)
    if label:
        widget = HTML.label(widget, label)
    return widget
Exemplo n.º 7
0
def error_container(name, as_text=False):
    return HTML.tag('span',
                    class_='error %s hidden' %
                    ('fa fa-arrow-circle-down as-text'
                     if as_text else 'fa fa-exclamation-circle'),
                    c=HTML.tag('span'),
                    **{'data-name': name})
Exemplo n.º 8
0
 def test_multiple_optimizations(self):
     a = {"class_": ["A", "B"], "style": ["C", "D"], "bad": None}
     b = {
         "class": "A B",
         "style": "C; D",
     }
     HTML.optimize_attrs(a)
     assert a == b
Exemplo n.º 9
0
def error_container(name, as_text=False):
    return HTML.tag(
        'span',
        class_='error %s hidden'
        % ('fa fa-arrow-circle-down as-text' if as_text else 'fa fa-exclamation-circle'),
        c=HTML.tag('span'),
        **{'data-name': name}
    )
Exemplo n.º 10
0
def _list(tag, items, default, attrs, li_attrs):
    content = [HTML.tag("li", x, **li_attrs) for x in items]
    if content:
        content = [""] + content + [""]
    elif default is not None:
        return default
    content = literal("\n").join(content)
    return HTML.tag(tag, content, **attrs)
Exemplo n.º 11
0
def _list(tag, items, default, attrs, li_attrs):
    content = [HTML.tag("li", x, **li_attrs) for x in items]
    if content:
        content = [""] + content + [""]
    elif default is not None:
        return default
    content = literal("\n").join(content)
    return HTML.tag(tag, content, **attrs)
Exemplo n.º 12
0
def contact_type_icon(contact_type):
    assert contact_type.key in (u'phone', u'email', u'skype'), \
        u"wrong contact type"
    if contact_type.key == u'phone':
        return HTML.tag('span', class_='fa fa-phone')
    elif contact_type.key == u'email':
        return HTML.tag('span', class_='fa fa-envelope')
    else:
        return HTML.tag('span', class_='fa fa-skype')
Exemplo n.º 13
0
 def test_html(self):
     a = HTML.a(href='http://mostlysafe\" <tag', c="Bad <script> tag")
     assert a == '<a href="http://mostlysafe&#34; &lt;tag">Bad &lt;script&gt; tag</a>'
     
     img = HTML.img(src="http://some/image.jpg")
     assert img == '<img src="http://some/image.jpg" />'
     
     br = HTML.br()
     assert "<br />" == br
Exemplo n.º 14
0
def test_html():
    a = HTML.a(href='http://mostlysafe\" <tag', c="Bad <script> tag")
    eq_(a, u'<a href="http://mostlysafe&#34; &lt;tag">Bad &lt;script&gt; tag</a>')
    
    img = HTML.img(src='http://some/image.jpg')
    eq_(img, u'<img src="http://some/image.jpg" />')
    
    br = HTML.br()
    eq_(u'<br />', br)
Exemplo n.º 15
0
def contact_type_icon(contact_type):
    assert contact_type.key in (u'phone', u'email', u'skype'), \
        u"wrong contact type"
    if contact_type.key == u'phone':
        return HTML.tag('span', class_='fa fa-phone')
    elif contact_type.key == u'email':
        return HTML.tag('span', class_='fa fa-envelope')
    else:
        return HTML.tag('span', class_='fa fa-skype')
Exemplo n.º 16
0
 def test_html(self):
     a = HTML.a(href='http://mostlysafe\" <tag', c="Bad <script> tag")
     assert a == '<a href="http://mostlysafe&#34; &lt;tag">Bad &lt;script&gt; tag</a>'
     
     img = HTML.img(src="http://some/image.jpg")
     assert img == '<img src="http://some/image.jpg" />'
     
     br = HTML.br()
     assert "<br />" == br
Exemplo n.º 17
0
def boolicon(value):
    """Returns boolean value of a value, represented as small html image of true/false
    icons

    :param value: value
    """

    if value:
        return HTML.tag('i', class_="icon-ok")
    else:
        return HTML.tag('i', class_="icon-minus-circled")
Exemplo n.º 18
0
 def options_td(col_num, i, item):
     href = self.request.route_url(
         "admin_object", object="users", object_id=item.id, verb="GET"
     )
     edit_link = HTML.a(translate(_("Edit")), class_="btn btn-info", href=href)
     delete_href = self.request.route_url(
         "admin_object", object="users", object_id=item.id, verb="DELETE"
     )
     delete_link = HTML.a(
         translate(_("Delete")), class_="btn btn-danger", href=delete_href
     )
     return HTML.td(edit_link, " ", delete_link, class_="c{}".format(col_num))
Exemplo n.º 19
0
 def options_td(col_num, i, item):
     href = self.request.route_url(
         'admin_object_relation',
         object='users',
         object_id=self.additional_kw['user'].id,
         verb='DELETE',
         relation='permissions',
         _query={'perm_name': item.perm_name})
     delete_link = HTML.a(translate(_('Delete')),
                          class_='btn btn-danger',
                          href=href)
     return HTML.td(delete_link, class_='c{}'.format(col_num))
Exemplo n.º 20
0
 def options_td(col_num, i, item):
     href = self.request.route_url(
         "admin_object_relation",
         object="users",
         object_id=self.additional_kw["user"].id,
         verb="DELETE",
         relation="permissions",
         _query={"perm_name": item.perm_name},
     )
     delete_link = HTML.a(
         translate(_("Delete")), class_="btn btn-danger", href=href
     )
     return HTML.td(delete_link, class_="c{}".format(col_num))
Exemplo n.º 21
0
def button(context, permision, caption, **kwargs):
    html = ''
    if context.has_permision(permision):
        caption = HTML.tag('span', c=caption)
        icon = ''
        if 'icon' in kwargs:
            icon = HTML.tag('span', class_=kwargs.pop('icon'))
        button_class = "button _action " + kwargs.pop('class', '')
        button_class = button_class.strip()
        html = HTML.tag(
            'a', class_=button_class,
            c=HTML(icon, caption), **kwargs
        )
    return html
Exemplo n.º 22
0
def js_obfuscate(content):
    """Obfuscate data in a Javascript tag.
    
    Example::
        
        >>> js_obfuscate("<input type='hidden' name='check' value='valid' />")
        literal(u'<script type="text/javascript">\\n//<![CDATA[\\neval(unescape(\\'%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%69%6e%70%75%74%20%74%79%70%65%3d%27%68%69%64%64%65%6e%27%20%6e%61%6d%65%3d%27%63%68%65%63%6b%27%20%76%61%6c%75%65%3d%27%76%61%6c%69%64%27%20%2f%3e%27%29%3b\\'))\\n//]]>\\n</script>')
        
    """
    doc_write = "document.write(%s);" % js_quote_string(content)
    obfuscated = ''.join(['%%%x' % ord(x) for x in doc_write])
    complete = "eval(unescape('%s'))" % obfuscated
    cdata = HTML.cdata("\n", complete, "\n//")
    return HTML.tag("script", "\n//", cdata, "\n", type="text/javascript")
Exemplo n.º 23
0
 def _render(self, options, selected_values):
     tags = []
     for opt in options:
         if isinstance(opt, OptGroup):
             content = self._render(opt, selected_values)
             tag = HTML.tag("optgroup", NL, content, label=opt.label)
             tags.append(tag)
         else:
             value = opt.value if opt.value is not None else opt.label
             selected = value in selected_values
             tag = HTML.tag("option", opt.label, value=opt.value,
                 selected=selected)
             tags.append(tag)
     return HTML(*tags, nl=True)
Exemplo n.º 24
0
 def test_literal(self):
     lit = literal("This string <>")
     other = literal("<other>")
     assert "This string <><other>" == lit + other
     assert type(lit + other) is literal
     
     assert "&#34;<other>" == '"' + other
     assert "<other>&#34;" == other + '"'
     
     mod = literal("<%s>ello")
     assert "<&lt;H&gt;>ello" == mod % "<H>"
     assert type(mod % "<H>") is literal
     assert HTML("<a>") == "&lt;a&gt;"
     assert type(HTML("<a>")) is literal
Exemplo n.º 25
0
def button(context, permision, caption, **kwargs):
    html = ''
    if context.has_permision(permision):
        caption = HTML.tag('span', c=caption)
        icon = ''
        if 'icon' in kwargs:
            icon = HTML.tag('span', class_=kwargs.pop('icon'))
        button_class = "button _action " + kwargs.pop('class', '')
        button_class = button_class.strip()
        html = HTML.tag('a',
                        class_=button_class,
                        c=HTML(icon, caption),
                        **kwargs)
    return html
Exemplo n.º 26
0
def js_obfuscate(content):
    """Obfuscate data in a Javascript tag.
    
    Example::
        
        >>> js_obfuscate("<input type='hidden' name='check' value='valid' />")
        literal(u'<script type="text/javascript">\\n//<![CDATA[\\neval(unescape(\\'%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%69%6e%70%75%74%20%74%79%70%65%3d%27%68%69%64%64%65%6e%27%20%6e%61%6d%65%3d%27%63%68%65%63%6b%27%20%76%61%6c%75%65%3d%27%76%61%6c%69%64%27%20%2f%3e%27%29%3b\\'))\\n//]]>\\n</script>')
        
    """
    doc_write = "document.write('%s');" % content
    obfuscated = ''.join(['%%%x' % ord(x) for x in doc_write])
    complete = "eval(unescape('%s'))" % obfuscated
    cdata = HTML.cdata("\n", complete, "\n//")
    return HTML.script("\n//", cdata, "\n", type="text/javascript")
Exemplo n.º 27
0
def title(title, required=False, label_for=None):
    """Format the user-visible title for a form field.

    Use this for forms that have a text title above or next to each
    field.

    ``title`` -- the name of the field; e.g., "First Name".

    ``required`` -- if true, append a \*" to the title and use the
    'required' HTML format (see example); otherwise use the 'not
    required' format.

    ``label_for`` -- if provided, put ``<label for="ID">`` around the
    title.  The value should be the HTML ID of the input field related
    to this title.  Per the HTML standard, the ID should point to a
    single control (input, select, textarea), not to multiple controls
    (fieldset, group of checkboxes, group of radio buttons).  ID's are
    set by passing the keyword arg ``id`` to the appropriate helper.
    
    Note that checkboxes and radio buttions typically have their own
    individual labels in addition to the title.  You can set these with
    the ``label`` argument to ``checkbox()`` and ``radio()``.

    This helper does not accept other keyword arguments.

    See webhepers2/static/stylesheets/webhelpers2.css for suggested styles.

    >>> title("First Name")
    literal(u'<span class="not-required">First Name</span>')
    >>> title("Last Name", True)
    literal(u'<span class="required">Last Name <span class="required-symbol">*</span></span>')
    >>> title("First Name", False, "fname")
    literal(u'<span class="not-required"><label for="fname">First Name</label></span>')
    >>> title("Last Name", True, label_for="lname")
    literal(u'<span class="required"><label for="lname">Last Name</label> <span class="required-symbol">*</span></span>')
    """
    title_html = title
    required_html = literal("")
    if label_for:
        title_html = HTML.label(title_html, for_=label_for)
    if required:
        required_symbol = HTML.span("*", class_="required-symbol")
        return HTML.span(
            title_html, 
            " ",
            required_symbol,
            class_="required")
    else:
        return HTML.span(title_html, class_="not-required")
Exemplo n.º 28
0
def th_sortable(current_order, column_order, label, url,
    class_if_sort_column="sort", class_if_not_sort_column=None, 
    link_attrs=None, name="th", **attrs):
    """<th> for a "click-to-sort-by" column.

    Convenience function for a sortable column.  If this is the current sort
    column, just display the label and set the cell's class to
    ``class_if_sort_column``.
    
    ``current_order`` is the table's current sort order.  ``column_order`` is
    the value pertaining to this column.  In other words, if the two are equal,
    the table is currently sorted by this column.

    If this is the sort column, display the label and set the <th>'s class to
    ``class_if_sort_column``.

    If this is not the sort column, display an <a> hyperlink based on
    ``label``, ``url``, and ``link_attrs`` (a dict), and set the <th>'s class
    to ``class_if_not_sort_column``.  
    
    ``url`` is the literal href= value for the link.  Pylons users would
    typically pass something like ``url=h.url_for("mypage", sort="date")``.

    ``**attrs`` are additional attributes for the <th> tag.

    If you prefer a <td> tag instead of <th>, pass ``name="td"``.

    To change the sort order via client-side Javascript, pass ``url=None`` and
    the appropriate Javascript attributes in ``link_attrs``.

    Examples:

    >>> sort = "name"
    >>> th_sortable(sort, "name", "Name", "?sort=name")
    literal(u'<th class="sort">Name</th>')
    >>> th_sortable(sort, "date", "Date", "?sort=date")
    literal(u'<th><a href="?sort=date">Date</a></th>')
    >>> th_sortable(sort, "date", "Date", None, link_attrs={"onclick": "myfunc()"})
    literal(u'<th><a onclick="myfunc()">Date</a></th>')
    """
    from webhelpers2.html import HTML
    if current_order == column_order:
        content = label
        class_ = class_if_sort_column
    else:
        link_attrs = link_attrs or {}
        content = HTML.tag("a", label, href=url, **link_attrs)
        class_ = class_if_not_sort_column
    return HTML.tag("th", content, class_=class_, **attrs)
Exemplo n.º 29
0
 def render_static(self):
     self.add_attr('class', 'textarea')
     if self.displayval == '':
         todisplay = literal('&nbsp;')
     else:
         todisplay = self.displayval
     return HTML.span(todisplay, **self._static_attributes())
Exemplo n.º 30
0
        def options_td(col_num, i, item):
            if item.owner is True:
                return HTML.td("", class_="c{}".format(col_num))

            href = self.request.route_url(
                "admin_object_relation",
                object="resources",
                object_id=item.resource.resource_id,
                verb="DELETE",
                relation="group_permissions",
                _query={"perm_name": item.perm_name, "group_id": item.group.id},
            )
            delete_link = HTML.a(
                translate(_("Delete")), class_="btn btn-danger", href=href
            )
            return HTML.td(delete_link, class_="c{}".format(col_num))
Exemplo n.º 31
0
 def test_tag(self):
     a = HTML.tag("a",
                  href="http://www.yahoo.com",
                  name=None,
                  c="Click Here")
     b = literal('<a href="http://www.yahoo.com">Click Here</a>')
     self.check(a, b)
Exemplo n.º 32
0
def stylesheet_link(*urls, **attrs):
    """Return CSS link tags for the specified stylesheet URLs.

    ``urls`` should be the exact URLs desired.  A previous version of this
    helper added magic prefixes; this is no longer the case.

    Examples::

        >>> stylesheet_link('/stylesheets/style.css')
        literal(u'<link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />')

        >>> stylesheet_link('/stylesheets/dir/file.css', media='all')
        literal(u'<link href="/stylesheets/dir/file.css" media="all" rel="stylesheet" type="text/css" />')

    """
    if "href" in attrs:
        raise TypeError("keyword arg 'href' not allowed")
    attrs.setdefault("rel", "stylesheet")
    attrs.setdefault("type", "text/css")
    attrs.setdefault("media", "screen")
    tags = []
    for url in urls:
        tag = HTML.tag("link", href=url, **attrs)
        tags.append(tag)
    return literal('\n').join(tags)
Exemplo n.º 33
0
def javascript_link(*urls, **attrs):
    """Return script include tags for the specified javascript URLs.
    
    ``urls`` should be the exact URLs desired.  A previous version of this
    helper added magic prefixes; this is no longer the case.

    Specify the keyword argument ``defer=True`` to enable the script 
    defer attribute.

    Examples::
    
        >>> print javascript_link('/javascripts/prototype.js', '/other-javascripts/util.js')
        <script src="/javascripts/prototype.js" type="text/javascript"></script>
        <script src="/other-javascripts/util.js" type="text/javascript"></script>

        >>> print javascript_link('/app.js', '/test/test.1.js')
        <script src="/app.js" type="text/javascript"></script>
        <script src="/test/test.1.js" type="text/javascript"></script>
        
    """
    tags = []
    for url in urls:
        tag = HTML.tag("script", "", type="text/javascript", src=url, **attrs)
        tags.append(tag)
    return literal("\n").join(tags)
Exemplo n.º 34
0
def date_field(name, value=None, data_options=None, **kwargs):
    id = gen_id()
    format = get_date_format()
    
    # this hack is need for datebox correct working
    format = format.replace('yy', 'yyyy')

    _data_options = """
        editable:false,
        formatter:function(date){return dt_formatter(date, %s);},
        parser:function(s){return dt_parser(s, %s);}
        """ % (
       jsonify(format),
       jsonify(format)
    )
    if data_options:
        _data_options += ",%s" % data_options
    if value:
        value = format_date(value, format)
    html = tags.text(
        name, value, class_="easyui-datebox text w10",
        id=id, data_options=_data_options, **kwargs
    )
    return html + HTML.literal("""
        <script type="text/javascript">
            add_datebox_clear_btn("#%s");
        </script>
    """) % id
Exemplo n.º 35
0
def _input(type, name, value, id, attrs):
    """Finish rendering an input tag."""
    attrs["type"] = type
    attrs["name"] = name
    attrs["value"] = value
    _set_id_attr(attrs, id, name)
    return HTML.tag("input", **attrs)
Exemplo n.º 36
0
def image(url, alt, width=None, height=None, **attrs):
    """Return an image tag for the specified ``source``.

    ``url``
        The URL of the image.  (This must be the exact URL desired.  A
        previous version of this helper added magic prefixes; this is
        no longer the case.)
    
    ``alt``
        The img's alt tag. Non-graphical browsers and screen readers will
        output this instead of the image.  If the image is pure decoration
        and uninteresting to non-graphical users, pass "".  To omit the
        alt tag completely, pass None.

    ``width``
        The width of the image, default is not included.

    ``height``
        The height of the image, default is not included.

    Note: This version does not support the 'path' and 'use_pil' arguments,
    because they depended on the WebHelpers 'media' subpackage which was
    dropped in WebHelpers 2. 
    """
    if "path" in attrs:
        raise TypeError("the 'path' arg is not supported in WebHelpers2")
    if "use_pil" in attrs:
        raise TypeError("the 'use_pil' arg is not supported in WebHelpers2")
    if not alt:
        alt = ""
    if width is not None or height is not None:
        attrs['width'] = width
        attrs['height'] = height
    return HTML.tag("img", src=url, alt=alt, **attrs)
Exemplo n.º 37
0
def _input(type, name, value, id, attrs):
    """Finish rendering an input tag."""
    attrs["type"] = type
    attrs["name"] = name
    attrs["value"] = value
    _set_id_attr(attrs, id, name)
    return HTML.tag("input", **attrs)
Exemplo n.º 38
0
 def _render(self, options, selected_values):
     tags = []
     for opt in options:
         if isinstance(opt, OptGroup):
             content = self._render(opt, selected_values)
             tag = HTML.tag("optgroup", NL, content, label=opt.label)
             tags.append(tag)
         else:
             value = opt.value if opt.value is not None else opt.label
             selected = value in selected_values
             tag = HTML.tag("option",
                            opt.label,
                            value=opt.value,
                            selected=selected)
             tags.append(tag)
     return HTML(*tags, nl=True)
Exemplo n.º 39
0
def radio(name, value, checked=False, label=None, label_class=None, **attrs):
    """Create a radio button.

    Arguments:
    ``name`` -- the field's name.

    ``value`` -- the value returned to the application if the button is
    pressed.

    ``checked`` -- true if the button should be initially pressed.

    ``label`` -- a text label to display to the right of the button.
    This puts a <label> tag around the input tag.
    
    ``label_class`` -- CSS class for <label> tag. This should be a keyword
    argument because its position may change in a future version.

    The id of the radio button will be set to the name + '_' + value to 
    ensure its uniqueness.  An ``id`` keyword arg overrides this.  (Note
    that this behavior is unique to the ``radio()`` helper.)
    
    To arrange multiple radio buttons in a group, see
    webhelpers2.containers.distribute().
    """
    if checked:
        attrs["checked"] = "checked"
    if not "id" in attrs:
        attrs["id"] = "{0}_{1}".format(name, _make_safe_id_component(value))
    # Pass None as 'id' arg to '_input()' to prevent further modification of
    # the 'id' attribute.
    widget = _input("radio", name, value, None, attrs)
    if label:
        widget = HTML.tag("label", widget, " ", label, class_=label_class)
    return widget
Exemplo n.º 40
0
def radio(name, value, checked=False, label=None, label_class=None, **attrs):
    """Create a radio button.

    Arguments:
    ``name`` -- the field's name.

    ``value`` -- the value returned to the application if the button is
    pressed.

    ``checked`` -- true if the button should be initially pressed.

    ``label`` -- a text label to display to the right of the button.
    This puts a <label> tag around the input tag.
    
    ``label_class`` -- CSS class for <label> tag. This should be a keyword
    argument because its position may change in a future version.

    The id of the radio button will be set to the name + '_' + value to 
    ensure its uniqueness.  An ``id`` keyword arg overrides this.  (Note
    that this behavior is unique to the ``radio()`` helper.)
    
    To arrange multiple radio buttons in a group, see
    webhelpers2.containers.distribute().
    """
    if checked:
        attrs["checked"] = "checked"
    if not "id" in attrs:
        attrs["id"] = "{0}_{1}".format(name, _make_safe_id_component(value))
    # Pass None as 'id' arg to '_input()' to prevent further modification of
    # the 'id' attribute.
    widget = _input("radio", name, value, None, attrs)
    if label:
        widget = HTML.tag("label", widget, " ", label, class_=label_class)
    return widget
Exemplo n.º 41
0
def image(url, alt, width=None, height=None, **attrs):
    """Return an image tag for the specified ``source``.

    ``url``
        The URL of the image.  (This must be the exact URL desired.  A
        previous version of this helper added magic prefixes; this is
        no longer the case.)
    
    ``alt``
        The img's alt tag. Non-graphical browsers and screen readers will
        output this instead of the image.  If the image is pure decoration
        and uninteresting to non-graphical users, pass "".  To omit the
        alt tag completely, pass None.

    ``width``
        The width of the image, default is not included.

    ``height``
        The height of the image, default is not included.

    Note: This version does not support the 'path' and 'use_pil' arguments,
    because they depended on the WebHelpers 'media' subpackage which was
    dropped in WebHelpers 2. 
    """
    if "path" in attrs:
        raise TypeError("the 'path' arg is not supported in WebHelpers2")
    if "use_pil" in attrs:
        raise TypeError("the 'use_pil' arg is not supported in WebHelpers2")
    if not alt:
        alt = ""
    if width is not None or height is not None:
        attrs['width'] = width
        attrs['height'] = height
    return HTML.tag("img", src=url, alt=alt, **attrs)
Exemplo n.º 42
0
def auto_discovery_link(url, feed_type="rss", **attrs):
    """Return a link tag allowing auto-detecting of RSS or ATOM feed.
    
    The auto-detection of feed for the current page is only for
    browsers and news readers that support it.

    ``url``
        The URL of the feed.  (This should be the exact URLs desired.  A
        previous version of this helper added magic prefixes; this is no longer
        the case.)

    ``feed_type``
        The type of feed. Specifying 'rss' or 'atom' automatically 
        translates to a type of 'application/rss+xml' or 
        'application/atom+xml', respectively. Otherwise the type is
        used as specified. Defaults to 'rss'.
    """
    if "href" in attrs:
        raise TypeError("keyword arg 'href' is not allowed")
    if "type" in attrs:
        raise TypeError("keyword arg 'type' is not allowed")
    title = ""
    if feed_type.lower() in ('rss', 'atom'):
        title = feed_type.upper()
        feed_type = 'application/{0}+xml'.format(feed_type.lower())
    attrs.setdefault("title", title)
    return HTML.tag("link", rel="alternate", type=feed_type, href=url, **attrs)
Exemplo n.º 43
0
def auto_discovery_link(url, feed_type="rss", **attrs):
    """Return a link tag allowing auto-detecting of RSS or ATOM feed.
    
    The auto-detection of feed for the current page is only for
    browsers and news readers that support it.

    ``url``
        The URL of the feed.  (This should be the exact URLs desired.  A
        previous version of this helper added magic prefixes; this is no longer
        the case.)

    ``feed_type``
        The type of feed. Specifying 'rss' or 'atom' automatically 
        translates to a type of 'application/rss+xml' or 
        'application/atom+xml', respectively. Otherwise the type is
        used as specified. Defaults to 'rss'.
    """
    if "href" in attrs:
        raise TypeError("keyword arg 'href' is not allowed")
    if "type" in attrs:
        raise TypeError("keyword arg 'type' is not allowed")
    title = ""
    if feed_type.lower() in ('rss', 'atom'):
        title = feed_type.upper()
        feed_type = 'application/{0}+xml'.format(feed_type.lower())
    attrs.setdefault("title", title)
    return HTML.tag("link", rel="alternate", type=feed_type, href=url, **attrs)
Exemplo n.º 44
0
    def table_tr_output(self, cells, row_hah):
        # do some formatting so that the source code is properly indented
        tds_str = u'\n'.join(cells)
        tds_str = reindent(tds_str, 12)
        tds_str = u'\n{0}\n        '.format(tds_str)

        return _HTML.tr(literal(tds_str), **row_hah)
Exemplo n.º 45
0
 def begin_row(self):
     self.element.set_attr('id', '%s-%s' % (self.element.getidattr(), self.wrap_type))
     class_str = '%s%s%s' % (self.wrap_type, self.alt_class(), self.first_class())
     self.element.add_attr('class', class_str)
     # HTML.tag should not close the div
     attrs = self.element.get_attrs()
     attrs['_closed'] = False
     self.output.inc(HTML.tag('div', **attrs))
Exemplo n.º 46
0
def link_to_unless(condition, label, url='', **attrs):
    """The opposite of ``link_to``. Return just the label if the condition is 
    true.
    """
    if not condition:
        return link_to(label, url, **attrs)
    else:
        return HTML(label)
Exemplo n.º 47
0
 def link_css_url(self, url, **kwargs):
     if not kwargs.pop('relative_path', False):
         url = abs_static_url(url)
     else:
         url = static_url(url)
     link_tag = HTML.link(rel='stylesheet', type='text/css', href=url, **kwargs)
     self.data['x-link-tags'].append(link_tag)
     return u''
Exemplo n.º 48
0
 def source_js_url(self, url, **kwargs):
     if not kwargs.pop('relative_path', False):
         url = abs_static_url(url)
     else:
         url = static_url(url)
     script_tag = HTML.script(type='text/javascript', src=url, **kwargs)
     self.data['x-script-tags'].append(script_tag)
     return u''
Exemplo n.º 49
0
        def options_td(col_num, i, item):
            if item.owner is True:
                return HTML.td('', class_='c{}'.format(col_num))

            href = self.request.route_url('admin_object_relation',
                                          object='resources',
                                          object_id=item.resource.resource_id,
                                          verb='DELETE',
                                          relation='group_permissions',
                                          _query={
                                              'perm_name': item.perm_name,
                                              'group_id': item.group.id
                                          })
            delete_link = HTML.a(translate(_('Delete')),
                                 class_='btn btn-danger',
                                 href=href)
            return HTML.td(delete_link, class_='c{}'.format(col_num))
Exemplo n.º 50
0
 def options_td(col_num, i, item):
     href = self.request.route_url(
         "admin_object", object="users", object_id=item.id, verb="GET"
     )
     edit_link = HTML.a(translate(_("Edit")), class_="btn btn-info", href=href)
     href = self.request.route_url(
         "admin_object_relation",
         object="groups",
         object_id=self.additional_kw["group"].id,
         relation="users",
         verb="DELETE",
         _query={"user_id": item.id},
     )
     delete_link = HTML.a(
         translate(_("Delete")), class_="btn btn-danger", href=href
     )
     return HTML.td(edit_link, " ", delete_link, class_="c{}".format(col_num))
Exemplo n.º 51
0
def _list(tag, items, default, attrs, li_attrs):
    content = [HTML.li(x, **li_attrs) for x in items]
    if content:
        content = [""] + content + [""]
    elif default is not None:
        return default
    content = literal("\n").join(content)
    return getattr(HTML, tag)(content, **attrs)
Exemplo n.º 52
0
def nl2br(text):
    """Insert a <br /> before each newline.
    """
    if text is None:
        return literal("")
    text = lit_sub(_universal_newline_rx, "\n", text)
    text = HTML(text).replace("\n", br)
    return text
Exemplo n.º 53
0
def th_sortable(current_order,
                column_order,
                label,
                url,
                class_if_sort_column="sort",
                class_if_not_sort_column=None,
                link_attrs=None,
                name="th",
                **attrs):
    """<th> for a "click-to-sort-by" column.

    Convenience function for a sortable column.  If this is the current sort
    column, just display the label and set the cell's class to
    ``class_if_sort_column``.
    
    ``current_order`` is the table's current sort order.  ``column_order`` is
    the value pertaining to this column.  In other words, if the two are equal,
    the table is currently sorted by this column.

    If this is the sort column, display the label and set the <th>'s class to
    ``class_if_sort_column``.

    If this is not the sort column, display an <a> hyperlink based on
    ``label``, ``url``, and ``link_attrs`` (a dict), and set the <th>'s class
    to ``class_if_not_sort_column``.  
    
    ``url`` is the literal href= value for the link.  Pylons users would
    typically pass something like ``url=h.url_for("mypage", sort="date")``.

    ``**attrs`` are additional attributes for the <th> tag.

    If you prefer a <td> tag instead of <th>, pass ``name="td"``.

    To change the sort order via client-side Javascript, pass ``url=None`` and
    the appropriate Javascript attributes in ``link_attrs``.
    """
    from webhelpers2.html import HTML
    if current_order == column_order:
        content = label
        class_ = class_if_sort_column
    else:
        link_attrs = link_attrs or {}
        content = HTML.tag("a", label, href=url, **link_attrs)
        class_ = class_if_not_sort_column
    return HTML.tag("th", content, class_=class_, **attrs)
Exemplo n.º 54
0
def content_tag(name, content, **options):
    """
    Create a tag with content

    Takes the same keyword args as ``tag``

    Examples::

        >>> print(content_tag("p", "Hello world!"))
        <p>Hello world!</p>
        >>> print(content_tag("div", content_tag("p", "Hello world!"), class_="strong"))
        <div class="strong"><p>Hello world!</p></div>
    """
    if content is None:
        content = ''
    tag = HTML.tag(name, _closed=False, **options) + HTML(content) + literal(
        '</%s>' % name)
    return tag
Exemplo n.º 55
0
 def render_static(self):
     if self.displayval == '':
         todisplay = literal('&nbsp;')
     else:
         if self.displayval.startswith('http:') or self.displayval.startswith('https:'):
             todisplay = tags.link_to(self.displayval, self.displayval)
         else:
             todisplay = self.displayval
     return HTML.span(todisplay, **self._static_attributes())
Exemplo n.º 56
0
 def render_static(self):
     if self.etype in ('button', 'file', 'hidden', 'image', 'submit',
                       'reset', 'password'):
         return ''
     if self.displayval == '':
         todisplay = literal('&nbsp;')
     else:
         todisplay = self.displayval
     return HTML.span(todisplay, **self._static_attributes())
Exemplo n.º 57
0
def form(url, method="post", **attrs):
    """Like webhelpers.html.tags.form , but automatically adding
    session_csrf_secret_token for POST. The secret is thus never leaked in GET
    URLs.
    """
    form = insecure_form(url, method, **attrs)
    if method.lower() == 'get':
        return form
    return form + HTML.div(hidden(session_csrf_secret_name, session_csrf_secret_token()), style="display: none;")