Exemplo n.º 1
0
def test_unclosed_tag():
    result = HTML.form(_closed=False)
    print result
    assert u"<form>" == result

    result = HTML.form(_closed=False, action="hello")
    assert u'<form action="hello">' == result
Exemplo n.º 2
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.º 3
0
 def get_audio_tag(self, request):
     from webhelpers.html import HTML
     static_path = self.get_static_path(request)
     source_tag = HTML.tag('source', type_='audio/mp3', src=static_path)
     audio_tag = HTML.tag('audio', controls='controls', c=[source_tag])
     div_tag = HTML.tag('div', class_='mp3', c=[audio_tag])
     return div_tag
Exemplo n.º 4
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.º 5
0
 def _get_update_details(self, update):
     details = ''
     if update['status'] == 'stable':
         if update.get('updateid'):
             details += HTML.tag('a', c=update['updateid'], href='%s/%s' % (
                                 self._prod_url, update['updateid']))
         if update.get('date_pushed'):
             details += HTML.tag('br') + update['date_pushed']
         else:
             details += 'In process...'
     elif update['status'] == 'pending' and update.get('request'):
         details += 'Pending push to %s' % update['request']
         details += HTML.tag('br')
         details += HTML.tag('a', c="View update details >",
                             href="%s/%s" % (self._prod_url,
                                             update['title']))
     elif update['status'] == 'obsolete':
         for comment in update['comments']:
             if comment['author'] == 'bodhi':
                 if comment['text'].startswith('This update has been '
                                               'obsoleted by '):
                     details += \
                         'Obsoleted by %s' % HTML.tag(
                             'a', href='%s/%s' % (
                                 self._prod_url, update['title']),
                             c=comment['text'].split()[-1])
     return details
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
    webhelpers.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 _pagerlink(self, page, text):
        # Let the url_for() from webhelpers create a new link and set
        # the variable called 'page_param'. Example:
        # You are in '/foo/bar' (controller='foo', action='bar')
        # and you want to add a parameter 'page'. Then you
        # call the navigator method with page_param='page' and
        # the url_for() call will create a link '/foo/bar?page=...'
        # with the respective page number added.
        link_params = {}
        # Use the instance kwargs from Page.__init__ as URL parameters
        link_params.update(self.kwargs)
        # Add keyword arguments from pager() to the link as parameters
        link_params.update(self.pager_kwargs)
        link_params[self.page_param] = page

        # Get the URL generator
        if self._url_generator is not None:
            url_generator = self._url_generator
        else:
            try:
                import pylons
                url_generator = pylons.url.current
            except (ImportError, AttributeError):
                try:
                    import routes
                    url_generator = routes.url_for
                    config = routes.request_config()
                except (ImportError, AttributeError):
                    raise NotImplementedError("no URL generator available")
                else:
                    # if the Mapper is configured with explicit=True we have to fetch
                    # the controller and action manually
                    if config.mapper.explicit:
                        if hasattr(config, 'mapper_dict'):
                            for k, v in config.mapper_dict.items():
                                if k != self.page_param:
                                    link_params[k] = v

        # Create the URL to load a certain page
        link_url = url_generator(**link_params)

        if self.onclick:  # create link with onclick action for AJAX
            # Create the URL to load the page area part of a certain page (AJAX
            # updates)
            link_params[self.partial_param] = 1
            partial_url = url_generator(**link_params)
            try:  # if '%s' is used in the 'onclick' parameter (backwards compatibility)
                onclick_action = self.onclick % (partial_url,)
            except TypeError:
                onclick_action = Template(self.onclick).safe_substitute({
                    "partial_url": partial_url,
                    "page": page
                    })
            a_tag = HTML.a(text, href=link_url, onclick=onclick_action, **self.link_attr)
        else:  # return static link
            a_tag = HTML.a(text, href=link_url, **self.link_attr)
        li_tag = HTML.li(a_tag)
        return li_tag
Exemplo n.º 9
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.º 10
0
def test_html():
    a = HTML.a(href='http://mostlysafe" <tag', c="Bad <script> tag")
    assert u'<a href="http://mostlysafe&quot; &lt;tag">Bad &lt;script&gt; tag</a>' == a

    img = HTML.img(src="http://some/image.jpg")
    assert u'<img src="http://some/image.jpg" />' == img

    br = HTML.br()
    assert u"<br />" == br
Exemplo n.º 11
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.º 12
0
def input_submit_text_button(text=None, name=None, **html_options):
    if text is None:
        from pylons.i18n import _
        text = _('Save')
    if name is not None:
        html_options['name'] = name

    html_options.setdefault('class_', "btn-text")
    html_options.setdefault('value', text)
    return HTML.button(c=[HTML.span(text)], **html_options)
Exemplo n.º 13
0
 def _range(self, regexp_match):
     html = super(Page, self)._range(regexp_match)
     # Convert ..
     dotdot = "\.\."
     dotdot_link = HTML.li(HTML.a("...", href="#"), class_="disabled")
     html = re.sub(dotdot, dotdot_link, html)
     # Convert current page
     text = "%s" % self.page
     current_page_span = str(HTML.span(c=text, **self.curpage_attr))
     current_page_link = self._pagerlink(self.page, text, extra_attributes=self.curpage_attr)
     return re.sub(current_page_span, current_page_link, html)
Exemplo n.º 14
0
def sa_learned(value):
    "indicate learning status"
    if not value:
        HTML.span(_('N'), class_='negative')

    match = LEARN_RE.search(value)
    if match:
        return (HTML.span(_('Y'), class_='positive') +
            literal('&nbsp;') + '(%s)' % escape(match.group(1)))
    else:
        return HTML.span(_('N'), class_='negative')
Exemplo n.º 15
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.º 16
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.º 17
0
def h1(title, id=None, tag='h1', **attrs):
    """Returns an <h1> tag that links to itself.

    `title` is the text inside the tag.

    `id` is the HTML id to use; if none is provided, `title` will be munged
    into something appropriate.
    """
    if not id:
        id = sanitize_id(title)

    link = HTML.a(title, href='#' + id, class_='subtle')
    return HTML.tag(tag, link, id=id, **attrs)
Exemplo n.º 18
0
def checkbox(label, name, checked=False, **kwargs):
    kwargs['type'] = 'checkbox'
    kwargs['name'] = name
    if checked:
        kwargs['checked'] = 'checked'
    kwargs.setdefault('id', name)
    return HTML.div(class_='formField checkbox',
                    id='%s-field' % kwargs['id'],
                    c=[HTML.label(for_=name, c=[
                    HTML.input(**kwargs),
                    HTML.span(class_='labelText', c=[label])
                    ]),
                    HTML.literal('<form:error name="%s" />' % name)])
Exemplo n.º 19
0
Arquivo: helpers.py Projeto: HHS/ckan
    def _range(self, regexp_match):
        html = super(Page, self)._range(regexp_match)
        # Convert ..
        dotdot = '<span class="pager_dotdot">..</span>'
        dotdot_link = HTML.li(HTML.a('...', href='#'), class_='disabled')
        html = re.sub(dotdot, dotdot_link, html)

        # Convert current page
        text = '%s' % self.page
        current_page_span = str(HTML.span(c=text, **self.curpage_attr))
        current_page_link = self._pagerlink(self.page, text,
                                            extra_attributes=self.curpage_attr)
        return re.sub(current_page_span, current_page_link, html)
Exemplo n.º 20
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('img', src=url("/images/icons/accept.png"),
                        alt=_('True'))
    else:
        return HTML.tag('img', src=url("/images/icons/cancel.png"),
                        alt=_('False'))
Exemplo n.º 21
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.º 22
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.º 23
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)s'<th class="sort">Name</th>')
    >>> th_sortable(sort, "date", "Date", "?sort=date")
    literal(%(u)s'<th><a href="?sort=date">Date</a></th>')
    >>> th_sortable(sort, "date", "Date", None, link_attrs={"onclick": "myfunc()"})
    literal(%(u)s'<th><a onclick="myfunc()">Date</a></th>')
    """
    from webhelpers.html import HTML
    if current_order == column_order:
        content = label
        class_ = class_if_sort_column
    else:
        link_attrs = link_attrs or {}
        content = HTML.a(label, href=url, **link_attrs)
        class_ = class_if_not_sort_column
    return HTML.th(content, class_=class_, **attrs)
Exemplo n.º 24
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 webhepers/public/stylesheets/webhelpers.css for suggested styles.

    >>> title("First Name")
    literal(%(u)s'<span class="not-required">First Name</span>')
    >>> title("Last Name", True)
    literal(%(u)s'<span class="required">Last Name <span class="required-symbol">*</span></span>')
    >>> title("First Name", False, "fname")
    literal(%(u)s'<span class="not-required"><label for="fname">First Name</label></span>')
    >>> title("Last Name", True, label_for="lname")
    literal(%(u)s'<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.º 25
0
    def pager(self, format='~2~', page_param='page', partial_param='partial',
        show_if_single_page=False, separator=' ', onclick=None,
        symbol_first='<<', symbol_last='>>',
        symbol_previous='<', symbol_next='>',
        link_attr={'class': 'pager_link', 'rel': 'prerender'},
        curpage_attr={'class': 'pager_curpage'},
        dotdot_attr={'class': 'pager_dotdot'}, **kwargs):

        self.curpage_attr = curpage_attr
        self.separator = separator
        self.pager_kwargs = kwargs
        self.page_param = page_param
        self.partial_param = partial_param
        self.onclick = onclick
        self.link_attr = link_attr
        self.dotdot_attr = dotdot_attr

        # Don't show navigator if there is no more than one page
        if self.page_count == 0 or (self.page_count == 1 and not show_if_single_page):
            return ''

        from string import Template
        # Replace ~...~ in token format by range of pages
        result = re.sub(r'~(\d+)~', self._range, format)

        # Interpolate '%' variables
        result = Template(result).safe_substitute({
            'first_page': self.first_page,
            'last_page': self.last_page,
            'page': self.page,
            'page_count': self.page_count,
            'items_per_page': self.items_per_page,
            'first_item': self.first_item,
            'last_item': self.last_item,
            'item_count': self.item_count,
            'link_first': self.page > self.first_page and \
                    self._pagerlink(self.first_page, symbol_first) or '',
            'link_last': self.page < self.last_page and \
                    self._pagerlink(self.last_page, symbol_last) or '',
            'link_previous': self.previous_page and \
                    self._pagerlink(self.previous_page, symbol_previous) \
                    or HTML.span(symbol_previous, class_="yui-pg-previous"),
            'link_next': self.next_page and \
                    self._pagerlink(self.next_page, symbol_next) \
                    or HTML.span(symbol_next, class_="yui-pg-next")
        })

        return literal(result)
Exemplo n.º 26
0
    def add_updates_to_builds(self, builds):
        """Update a list of koji builds with the corresponding bodhi updates.

        This method makes a single query to bodhi, asking if it knows about
        any updates for a given list of koji builds.  For builds with existing
        updates, the `update` will be added to it's dictionary.

        Currently it also adds `update_details`, which is HTML for rendering
        the builds update options.  Ideally, this should be done client-side
        in the template (builds/templates/table_widget.mak).

        """
        start = datetime.now()
        updates = self.call('get_updates_from_builds', {
            'builds': ' '.join([b['nvr'] for b in builds])})
        if updates:
            # FIXME: Lets stop changing the upstream APIs by putting the
            # session id as the first element, and the results in the second.
            updates = updates[1]

        for build in builds:
            if build['nvr'] in updates:
                build['update'] = updates[build['nvr']]
                status = build['update']['status']
                details = ''
                # FIXME: ideally, we should just return the update JSON and do
                # this logic client-side in the template when the grid data
                # comes in.
                if status == 'stable':
                    details = 'Pushed to updates'
                elif status == 'testing':
                    details = 'Pushed to updates-testing'
                elif status == 'pending':
                    details = 'Pending push to %s' % build['update']['request']

                details += HTML.tag('br')
                details += HTML.tag('a', c="View update details >",
                                    href="%s/%s" % (self._prod_url,
                                                    build['update']['title']))
            else:
                details = HTML.tag('a', c='Push to updates >',
                                   href='%s/new?builds.text=%s' % (
                                       self._prod_url, build['nvr']))

            build['update_details'] = details

        log.debug(
            "Queried bodhi for builds in: %s" % (datetime.now() - start))
Exemplo n.º 27
0
    def _pagerlink(self, pagenr, text):
        """
        Create a URL that links to another page using url_for().

        Parameters:

        pagenr
            Number of the page that the link points to

        text
            Text to be printed in the A-HREF tag
        """
        # Let the url_for() from webhelpers create a new link and set
        # the variable called 'page_param'. Example:
        # You are in '/foo/bar' (controller='foo', action='bar')
        # and you want to add a parameter 'pagenr'. Then you
        # call the navigator method with page_param='pagenr' and
        # the url_for() call will create a link '/foo/bar?pagenr=...'
        # with the respective page number added.
        link_params = {}
        # Use the instance kwargs from Page.__init__ as URL parameters
        link_params.update(self.kwargs)
        # Add keyword arguments from pager() to the link as parameters
        link_params.update(self.pager_kwargs)
        link_params[self.page_param] = pagenr

        # Create the URL to load a certain page
        link_url = link_params.get('link', request.path_info)
	if '?' in link_url:
	        link_url = '%s&page=%s'%(link_url, pagenr)
	else:
	        link_url = '%s?page=%s'%(link_url, pagenr)

        # Create the URL to load the page area part of a certain page (AJAX updates)
        #link_params[self.partial_param] = 1
        partial_url = link_params.get('partial', '') #url_for(**link_params)

        if self.onclick: # create link with onclick action for AJAX
            try: # if '%s' is used in the 'onclick' parameter (backwards compatibility)
                onclick_action = self.onclick % (partial_url,)
            except TypeError:
                onclick_action = Template(self.onclick).safe_substitute({
                  "partial_url": partial_url,
                  "page": pagenr
                })
            return HTML.a(text, href=link_url, onclick=onclick_action, **self.link_attr)
        else: # return static link
            return HTML.a(text, href=link_url, **self.link_attr)
Exemplo n.º 28
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)s'<link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />')

        >>> stylesheet_link('/stylesheets/dir/file.css', media='all')
        literal(%(u)s'<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.link(href=url, **attrs)
        tags.append(tag)
    return literal('\n').join(tags)
Exemplo n.º 29
0
def form_end(*k, **p):
    """\
    End a form started with ``form_start()``
    >>> form_end()
    literal(u'</form></table>')
    """
    return HTML.tag("/table", _closed=False) + end_form(*k, **p)
Exemplo n.º 30
0
def company_choice(request, companies, cid):
    """
        Add the company choose menu
    """
    options = []
    for company in companies:
        if request.context.__name__ == 'company':
            url = request.current_route_path(id=company.id)
        else:
            url = request.route_path("company", id=company.id)

        name = company.name
        if not company.active:
            name += " (désactivée)"

        options.append((url, name))

    if request.context.__name__ == 'company':
        default = request.current_route_path(id=cid)
    else:
        default = request.route_path("company", id=cid)

    html_attrs = {
        'class': 'company-search',
        'id': "company-select-menu",
    }
    html_code = HTML.li(
        tags.select("companies", default, options, **html_attrs)
    )
    return HtmlItem(html=html_code)
Exemplo n.º 31
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.º 32
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 webhepers/public/stylesheets/webhelpers.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.º 33
0
    def threads(self):
        import sys
        import traceback
        items = sys._current_frames().items()
        dumps = []
        for thread, frame in items:
            dumps.append({
                "id": str(thread),
                "info": _get_info(frame),
                "trace": "\n".join(traceback.format_stack(frame)),
            })

        from webhelpers.html import HTML, literal
        out = literal()
        out += str(len(items)) + " threads:\n"
        for data in dumps:
            out += HTML.br()
            out += HTML.a(data["info"], href="#" + data["id"])
        for data in dumps:
            out += HTML.hr()
            out += HTML.a(data["id"] + ": " + HTML.b(data["info"]),
                          name=data["id"])
            out += HTML.p()
            out += HTML.pre(data["trace"])
        return out
Exemplo n.º 34
0
def dataset_link_from_activity(activity):
    href = dataset_href_from_activity(activity)
    if not href:
        return ''
    try:
        title = activity['data']['package']['title']
        return HTML.a(title, href=href)
    except KeyError:
        return ''
Exemplo n.º 35
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.º 36
0
def password(name, value=None, id=None, **attrs):
    """Create a password field.
    
    Takes the same options as ``text()``.
    
    """
    _set_input_attrs(attrs, "password", name, value)
    _set_id_attr(attrs, id, name)
    return HTML.input(**attrs)
Exemplo n.º 37
0
def bool2icon(value):
    """Returns True/False values represented as small html image of true/false
    icons

    :param value: bool value
    """

    if value is True:
        return HTML.tag('img',
                        src=url("/images/icons/accept.png"),
                        alt=_('True'))

    if value is False:
        return HTML.tag('img',
                        src=url("/images/icons/cancel.png"),
                        alt=_('False'))

    return value
Exemplo n.º 38
0
 def handle_match(matchobj):
     all = matchobj.group()
     before, prefix, link, after = matchobj.group(1, 2, 3, 4)
     if re.match(r'<a\s', before, re.I):
         return all
     text = literal(prefix + link)
     if prefix == "www.":
         prefix = "http://www."
     a_options = dict(href_attrs)
     a_options['href'] = literal(prefix + link)
     return literal(before) + HTML.a(text, **a_options) + literal(after)
Exemplo n.º 39
0
def checkbox(name, value="1", checked=False, label=None, id=None, **attrs):
    """Create a check box.

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

    ``value`` -- the value to return to the application if the box is checked.

    ``checked`` -- true if the box should be initially checked.

    ``label`` -- a text label to display to the right of the box.

    ``id`` is the HTML ID attribute, and should be passed as a keyword
    argument.  By default the ID is the same as the name filtered through
    ``_make_safe_id_component()``.  Pass the empty string ("") to suppress the
    ID attribute entirely.

d
    The following HTML attributes may be set by keyword argument:

    * ``disabled`` - If true, checkbox will be grayed out.

    * ``readonly`` - If true, the user will not be able to modify the checkbox.

    To arrange multiple checkboxes in a group, see
    webhelpers.containers.distribute().

    Example::
    
        >>> checkbox("hi")
        literal(u'<input id="hi" name="hi" type="checkbox" value="1" />')
    """
    _set_input_attrs(attrs, "checkbox", name, value)
    _set_id_attr(attrs, id, name)
    if checked:
        attrs["checked"] = "checked"
    convert_boolean_attrs(attrs, ["disabled", "readonly"])
    widget = HTML.input(**attrs)
    if label:
        widget = HTML.label(widget, label)
    return widget
Exemplo n.º 40
0
def textarea(name, content="", id=None, **attrs):
    """Create a text input area.
    
    Example::
    
        >>> textarea("body", "", cols=25, rows=10)
        literal(u'<textarea cols="25" id="body" name="body" rows="10"></textarea>')
    
    """
    attrs["name"] = name
    _set_id_attr(attrs, id, name)
    return HTML.textarea(content, **attrs)
Exemplo n.º 41
0
def format_paragraphs(text, preserve_lines=False):
    """Convert text to HTML paragraphs.

    ``text``:
        the text to convert.  Split into paragraphs at blank lines (i.e.,
        wherever two or more consecutive newlines appear), and wrap each
        paragraph in a <p>.

    ``preserve_lines``:
        If true, add <br />  before each single line break
    """
    if text is None:
        return literal("")
    text = lit_sub(_universal_newline_rx, "\n", text)
    paragraphs = _paragraph_rx.split(text)
    for i, para in enumerate(paragraphs):
        if preserve_lines:
            para = HTML(para)
            para = para.replace("\n", br)
        paragraphs[i] = HTML.p(para)
    return literal("\n\n").join(paragraphs)
Exemplo n.º 42
0
        def _pagerlink(pagenr, text):
            """
            Create a URL that links to another page using url_for().

            Parameters:
                
            pagenr
                Number of the page that the link points to

            text
                Text to be printed in the A-HREF tag
            """
            from routes import url_for
            # Let the url_for() from webhelpers create a new link and set
            # the variable called 'page_param'. Example:
            # You are in '/foo/bar' (controller='foo', action='bar')
            # and you want to add a parameter 'pagenr'. Then you
            # call the navigator method with page_param='pagenr' and
            # the url_for() call will create a link '/foo/bar?pagenr=...'
            # with the respective page number added.
            link_params = {}
            # Use the instance kwargs from Page.__init__ as URL parameters
            link_params.update(self.kwargs)
            # Add keyword arguments from pager() to the link as parameters
            link_params.update(kwargs)
            link_params[page_param] = pagenr
            # Create the URL to load a certain page
            link_url = url_for(**link_params)
            # Create the URL to load the page area part of a certain page (AJAX updates)
            link_params[partial_param] = 1
            partial_url = url_for(**link_params)

            if onclick:  # create link with onclick action for AJAX
                onclick_action = onclick % (partial_url, )
                return HTML.a(text,
                              href=link_url,
                              onclick=onclick_action,
                              **link_attr)
            else:  # return static link
                return HTML.a(text, href=link_url, **link_attr)
Exemplo n.º 43
0
def form(url, method="post", multipart=False, **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:

    ``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.

    ``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.
    
    Examples:

    >>> form("/submit")
    literal(u'<form action="/submit" method="post">')
    >>> form("/submit", method="get")
    literal(u'<form action="/submit" method="get">')
    >>> form("/submit", method="put")
    literal(u'<form action="/submit" method="post"><input name="_method" type="hidden" value="put" />')
    >>> form("/submit", "post", multipart=True) 
    literal(u'<form action="/submit" enctype="multipart/form-data" method="post">')
    """
    if multipart:
        attrs["enctype"] = "multipart/form-data"
    method_tag = literal("")
    if method.lower() in ['post', 'get']:
        attrs['method'] = method
    else:
        attrs['method'] = "post"
        method_tag = HTML.input(type="hidden", name="_method", value=method)
    attrs["action"] = url
    return HTML.form(method_tag, _closed=False, **attrs)
Exemplo n.º 44
0
 def _render_form_start(self):
     html = []
     html.append(HTML.tag("div", class_="formbar-form", _closed=False))
     html.append(
         HTML.tag("form",
                  _closed=False,
                  id=self._form._config.id,
                  role="form",
                  class_=self._form._config.css,
                  action=self._form._config.action,
                  method=self._form._config.method,
                  autocomplete=self._form._config.autocomplete,
                  enctype=self._form._config.enctype,
                  evalurl=self._form._eval_url or ""))
     # Add hidden field with csrf_token if this is not None.
     if self._form._csrf_token:
         html.append(
             HTML.tag("input",
                      type="hidden",
                      name="csrf_token",
                      value=self._form._csrf_token))
     return literal("").join(html)
Exemplo n.º 45
0
def frag_link(value, title='', class_='', href_tuple=([], {}), data=None): #*args, **kwargs
    href, href_frag = url_pair(gen_format='frag', *href_tuple[0], **href_tuple[1]) # generate standard and frag URL's
    kwargs = {'data-frag' : href_frag}
    if data:
        kwargs.update(dict([('data-'+k, v) for k,v in data.iteritems()]))
    return HTML.a(
        value ,
        href    = href ,
        class_  = class_ + ' link_new_frag' ,
        title   = title if title else value,
        ##onClick ="cb_frag($(this), '%s'); return false;" % href_frag ,
        **kwargs
    )
Exemplo n.º 46
0
def link_to_objects(text):
    """
    Scan a string for "blah blah Content #42 blah blah" and replace
    "Content #42" with a link to the object editor
    """
    output = HTML.literal()
    prev_word = None
    for word in text.split():
        if prev_word:
            id_match = re.match("#(\d+)", word)
            if id_match:
                output = output + HTML.a(
                        prev_word+" #"+id_match.group(1),
                        href="/admin/"+prev_word+"/models/"+id_match.group(1)+"/edit")
                word = None
            else:
                output = output + HTML.literal(prev_word)
            output = output + HTML.literal(" ")
        prev_word = word
    if prev_word:
        output = output + HTML.literal(prev_word)
    return output
Exemplo n.º 47
0
def link_to(label, url='', **attrs):
    """Create a hyperlink with the given text pointing to the URL.
    
    If the label is ``None`` or empty, the URL will be used as the label.

    This function does not modify the URL in any way.  The label will be
    escaped if it contains HTML markup.  To prevent escaping, wrap the label
    in a ``webhelpers.html.literal()``.
    """
    attrs['href'] = url
    if label == '' or label is None:
        label = url
    return HTML.a(label, **attrs)
Exemplo n.º 48
0
def test_newline_arg():
    eq_(HTML.a(), literal(u'<a></a>'))
    eq_(HTML.a(_nl=True), literal(u'<a>\n</a>\n'))
    eq_(HTML.a(_closed=False), literal(u'<a>'))
    eq_(HTML.a(_closed=False, _nl=True), literal(u'<a>\n'))
    eq_(HTML.a("A", "B", href="/"), literal(u'<a href="/">AB</a>'))
    eq_(HTML.a("A", "B", href="/", _nl=True),
        literal(u'<a href="/">\nA\nB\n</a>\n'))
Exemplo n.º 49
0
def obfuscate_email(email_address):
    '''Obfuscate an email address for web display (hex encode and delete last 6
    chars).

    Borrowed and simplified from webhelpers.html.tools.mail_to
    '''
    if not email_address:
        return ''
    # replace last 5 characters
    email_address_obfuscated = email_address[:-6] + '....'
    email_address_obfuscated = HTML.literal(''.join(
        ['&#%d;' % ord(x) for x in email_address_obfuscated]))

    return email_address_obfuscated
Exemplo n.º 50
0
def file(name, value=None, id=None, **attrs):
    """Create a file upload field.
    
    If you are using file uploads then you will also need to set the 
    multipart option for the form.

    Example::

        >>> file('myfile')
        literal(u'<input id="myfile" name="myfile" type="file" />')
    
    """
    _set_input_attrs(attrs, "file", name, value)
    _set_id_attr(attrs, id, name)
    return HTML.input(**attrs)
Exemplo n.º 51
0
def start_with_layout(url, method="post", multipart=False, table_class=None, **attrs):
    """\
    Start a form the way you would with ``start_form()`` but include the HTML
    necessary for the use of the ``fields()`` helper. 
    
    >>> start_with_layout('/action', method='post')
    literal(u'<form action="/action" method="post"><table>')
    >>> start_with_layout('/action', method='post', table_class='form')
    literal(u'<form action="/action" method="post"><table class="form">')
    """
    if table_class:
         return start_form(url, method, multipart, **attrs)+HTML.table(
             _closed=False, 
             class_=table_class,
         )
    else:
         return start_form(url, method, multipart, **attrs)+literal('<table>')
Exemplo n.º 52
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
        
    Examples::

        >>> image('/images/rss.png', 'rss syndication')
        literal(u'<img alt="rss syndication" src="/images/rss.png" />')

        >>> image('/images/xml.png', "")
        literal(u'<img alt="" src="/images/xml.png" />')

        >>> image("/images/icon.png", height=16, width=10, alt="Edit Entry")
        literal(u'<img alt="Edit Entry" height="16" src="/images/icon.png" width="10" />')

        >>> image("/icons/icon.gif", alt="Icon", width=16, height=16)
        literal(u'<img alt="Icon" height="16" src="/icons/icon.gif" width="16" />')

        >>> image("/icons/icon.gif", None, width=16)
        literal(u'<img alt="" src="/icons/icon.gif" width="16" />')
        
    """
    if not alt:
        alt = ""
    if width is not None:
        attrs['width'] = width
    if height is not None:
        attrs['height'] = height
    return HTML.img(src=url, alt=alt, **attrs)
Exemplo n.º 53
0
def company_choice(request, companies, cid):
    """
        Add the company choose menu
    """
    if request.context.__name__ == 'company':
        options = ((request.current_route_path(id=company.id), company.name)
                   for company in companies)
        default = request.current_route_path(id=cid)
    else:
        options = ((request.route_path("company", id=company.id), company.name)
                   for company in companies)
        default = request.route_path("company", id=cid)
    html_attrs = {
        'class': 'pull-left company-search',
        'id': "company-select-menu",
    }
    html_code = HTML.li(
        tags.select("companies", default, options, **html_attrs))
    return HtmlItem(html=html_code)
Exemplo n.º 54
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'.
        
    Examples::

        >>> auto_discovery_link('http://feed.com/feed.xml')
        literal(u'<link href="http://feed.com/feed.xml" rel="alternate" title="RSS" type="application/rss+xml" />')

        >>> auto_discovery_link('http://feed.com/feed.xml', feed_type='atom')
        literal(u'<link href="http://feed.com/feed.xml" rel="alternate" title="ATOM" type="application/atom+xml" />')

        >>> auto_discovery_link('app.rss', feed_type='atom', title='atom feed')
        literal(u'<link href="app.rss" rel="alternate" title="atom feed" type="application/atom+xml" />')

        >>> auto_discovery_link('/app.html', feed_type='text/html')
        literal(u'<link href="/app.html" rel="alternate" title="" type="text/html" />')
        
    """
    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/%s+xml' % feed_type.lower()
    attrs.setdefault("title", title)
    return HTML.link(rel="alternate", type=feed_type, href=url, **attrs)
Exemplo n.º 55
0
def text(name, value=None, id=NotGiven, type="text", **attrs):
    """Create a standard text field.
    
    ``value`` is a string, the content of the text field.

    ``id`` is the HTML ID attribute, and should be passed as a keyword
    argument.  By default the ID is the same as the name filtered through
    ``_make_safe_id_component()``.  Pass None to suppress the
    ID attribute entirely.

    ``type`` is the input field type, normally "text". You can override it
    for HTML 5 input fields that don't have their own helper; e.g.,
    "search", "email", "date".

    
    Options:
    
    * ``disabled`` - If set to True, the user will not be able to use
        this input.
    * ``size`` - The number of visible characters that will fit in the
        input.
    * ``maxlength`` - The maximum number of characters that the browser
        will allow the user to enter.
    
    The remaining keyword args will be standard HTML attributes for the tag.

    Example, a text input field::

        >>> text("address")
        literal(u'<input id="address" name="address" type="text" />')

    HTML 5 example, a color picker:

        >>> text("color", type="color")
        literal(u'<input id="color" name="color" type="color" />')
    
    """
    _set_input_attrs(attrs, type, name, value)
    _set_id_attr(attrs, id, name)
    convert_boolean_attrs(attrs, ["disabled"])
    return HTML.input(**attrs)
Exemplo n.º 56
0
    def select(self, name, option_tags='', show_errors=True, **options):
        """
        Creates a dropdown selection box

        ``option_tags`` is a string containing the option tags for the select box::

            >>> select("people", "<option>George</option>")
            '<select id="people" name="people"><option>George</option></select>'

        Options:

        * ``multiple`` - If set to true the selection will allow multiple choices.

        """
        o = {'name_': name}
        o.update(options)

        ret = HTML.select(option_tags, **o)
        if show_errors:
            ret += self.get_error(name)
        return ret
Exemplo n.º 57
0
    def _render_diff(self, newvalue, oldvalue):
        """Will return a HTML string showing the differences between the old
        and the new string.

        The new string will have some markup to show the differences between
        the given strings. Words which has been deleted in the new string
        are marked with a *span* tag with the class *formed-deleted-value*.
        Elements which are new in the new string are marked with a span tag
        having the class *formed-new-value*.

        :old: Old string
        :new: New string
        :returns: A HTML string showing the differences.

        """
        out = []
        mode = None
        d = difflib.Differ()
        old = unicode(newvalue).split(" ")
        new = unicode(oldvalue).split(" ")
        diff = d.compare(old, new)
        for x in diff:
            if x[0:2] == "+ " and mode != "new":
                if mode:
                    out.append(HTML.tag("/span", _closed=False))
                    mode = None
                out.append(
                    HTML.tag("span", _closed=False,
                             class_="formbar-new-value"))
                mode = "new"
            elif x[0:2] == "- " and mode != "del":
                if mode:
                    out.append(HTML.tag("/span", _closed=False))
                    mode = None
                out.append(
                    HTML.tag("span", _closed=False,
                             class_="formbar-del-value"))
                mode = "del"
            elif x[0:2] == "  ":
                if mode:
                    out.append(HTML.tag("/span", _closed=False))
                    mode = None
            elif x[0:2] == "? ":
                continue
            out.append("%s " % "".join(x[2::]))
        if mode:
            out.append(HTML.tag("/span", _closed=False))
        return literal("").join(out)
Exemplo n.º 58
0
    def handle_match(matchobj):
        # The pattern contains a space so we only find usernames that
        # has a whitespace in front, we save the spaced so we can but
        # it back after the transformation
        space, userid = matchobj.group(1, 2)
        #Force lowercase userid
        userid = userid.lower()
        if userid in users:
            user = users[userid]

            tag = {}
            tag['href'] = request.resource_url(meeting,
                                               '_userinfo',
                                               query={
                                                   'userid': userid
                                               }).replace(
                                                   request.application_url, '')
            tag['title'] = user.title
            tag['class'] = "inlineinfo"
            return space + HTML.a('@%s' % userid, **tag)
        else:
            return space + '@' + userid
Exemplo n.º 59
0
    def radio_button(self,
                     name,
                     value,
                     checked=False,
                     show_errors=True,
                     **options):
        """Creates a radio button.

        The id of the radio button will be set to the name + value with a _ in
        between to ensure its uniqueness.
        """
        pretty_tag_value = re.sub(r'\s', "_", '%s' % value)
        pretty_tag_value = re.sub(r'(?!-)\W', "", pretty_tag_value).lower()
        html_options = {'type': 'radio', 'name_': name, 'value': value}
        html_options.update(options)
        if checked:
            html_options["checked"] = "checked"

        ret = HTML.input(**html_options)
        if show_errors:
            self.get_error(name)
        return ret
Exemplo n.º 60
0
def tag(name, open=False, **options):
    """
    Returns an XHTML compliant tag of type ``name``.

    ``open``
        Set to True if the tag should remain open

    All additional keyword args become attribute/value's for the tag. To pass in Python
    reserved words, append _ to the name of the key. For attributes with no value (such as
    disabled and readonly), a value of True is permitted.

    Examples::

        >>> print tag("br")
        <br />
        >>> print tag("br", True)
        <br>
        >>> print tag("input", type="text")
        <input type="text" />
        >>> print tag("input", type='text', disabled='disabled')
        <input disabled="disabled" type="text" />
    """
    return HTML.tag(name, _closed=not open, **options)