Beispiel #1
0
def options_for_select(container, selected=None):
    """
    Create select options from a container (list, tuple, dict).
    
    Accepts a container (list, tuple, dict) and returns a string of 
    option tags. Given a container where the elements respond to first 
    and last (such as a two-element array), the "lasts" serve as option 
    values and the "firsts" as option text. Dicts are turned into this 
    form automatically, so the keys become "firsts" and values become 
    lasts. If ``selected`` is specified, the matching "last" or element 
    will get the selected option-tag. ``Selected`` may also be an array 
    of values to be selected when using a multiple select.
    
    Examples (call, result)::
    
        >>> options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
        '<option value="$">Dollar</option>\\n<option value="DKK">Kroner</option>'
        >>> options_for_select([ "VISA", "MasterCard" ], "MasterCard")
        '<option value="VISA">VISA</option>\\n<option value="MasterCard" selected="selected">MasterCard</option>'
        >>> options_for_select(dict(Basic="$20", Plus="$40"), "$40")
        '<option value="$20">Basic</option>\\n<option value="$40" selected="selected">Plus</option>'
        >>> options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"])
        '<option value="VISA" selected="selected">VISA</option>\\n<option value="MasterCard">MasterCard</option>\\n<option value="Discover" selected="selected">Discover</option>'

    Note: Only the option tags are returned.  You have to wrap this call 
    in a regular HTML select tag.
    
    """
    if hasattr(container, "values"):
        container = container.items()
        container.sort()

    if not isinstance(selected, (list, tuple)):
        selected = (selected,)

    options = []

    for elem in container:
        if isinstance(elem, (list, tuple)):
            name, value = elem
            n = html_escape(name)
            v = html_escape(value)
        else:
            name = value = elem
            n = v = html_escape(elem)

        # TODO: run timeit for this against content_tag('option', n, value=v, selected=value in selected)
        if value in selected:
            options.append('<option value="%s" selected="selected">%s</option>' % (v, n))
        else:
            options.append('<option value="%s">%s</option>' % (v, n))
    return "\n".join(options)
Beispiel #2
0
def options_for_select(container, selected=None):
    """
    Create select options from a container (list, tuple, dict).
    
    Accepts a container (list, tuple, dict) and returns a string of 
    option tags. Given a container where the elements respond to first 
    and last (such as a two-element array), the "lasts" serve as option 
    values and the "firsts" as option text. Dicts are turned into this 
    form automatically, so the keys become "firsts" and values become 
    lasts. If ``selected`` is specified, the matching "last" or element 
    will get the selected option-tag. ``Selected`` may also be an array 
    of values to be selected when using a multiple select.
    
    Examples (call, result)::
    
        >>> options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
        '<option value="$">Dollar</option>\\n<option value="DKK">Kroner</option>'
        >>> options_for_select([ "VISA", "MasterCard" ], "MasterCard")
        '<option value="VISA">VISA</option>\\n<option value="MasterCard" selected="selected">MasterCard</option>'
        >>> options_for_select(dict(Basic="$20", Plus="$40"), "$40")
        '<option value="$20">Basic</option>\\n<option value="$40" selected="selected">Plus</option>'
        >>> options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"])
        '<option value="VISA" selected="selected">VISA</option>\\n<option value="MasterCard">MasterCard</option>\\n<option value="Discover" selected="selected">Discover</option>'

    Note: Only the option tags are returned.  You have to wrap this call 
    in a regular HTML select tag.
    
    """
    if hasattr(container, 'values'):
        container = container.items()
        container.sort()
    
    if not isinstance(selected, (list, tuple)):
        selected = (selected,)
    
    options = []
    
    for elem in container:
        if isinstance(elem, (list, tuple)):
            name, value = elem
            n = html_escape(name)
            v = html_escape(value)
        else:
            name = value = elem
            n = v = html_escape(elem)
        
        #TODO: run timeit for this against content_tag('option', n, value=v, selected=value in selected)
        if value in selected:
            options.append('<option value="%s" selected="selected">%s</option>' % (v, n))
        else:
            options.append('<option value="%s">%s</option>' % (v, n))
    return "\n".join(options)
Beispiel #3
0
    def install_config_form(self):
        """
        This method will be called to build setup configuration form.
        If this plugin needs parameters, provides form fields here.
        Any html and javascript are welcome.
        """
        if self.get_config(self.key_switch)=="no":
            enable_checked  = ""
            disable_checked = "checked"
        else:
            enable_checked  = "checked"
            disable_checked = ""

        result = ""
        result += "<p><strong>%s</strong></p>" % _("Fill this form")
        result += "<blockquote>"
        result += "<dl>"
        result += "\n<dt>"
        result += _("Enable email notify.")
        result += "\n<dd>"
        result += "<input type='radio' name='switch' value='yes' " + \
                enable_checked  + ">" + _("Enable") + "&nbsp;"
        result += "<input type='radio' name='switch' value='no' " + \
                disable_checked + ">" + _("Disable") + "<br>"
        result += "\n<dt>"
        result += _("Input email notify configurations: ")
        result += "\n<dd>"
        result += "<textarea name='config' rows='5' cols='40'>"
        result += html_escape(self.get_config(self.key_config))
        result += "</textarea>"
        result += "\n</dl>"
        result += "</blockquote>"
        return result
Beispiel #4
0
def form(url, method="post", multipart=False, **options):
    """
    Starts a form tag that points the action to an url. 
    
    The url options should be given either as a string, or as a ``url()``
    function. The method for the form defaults to POST.
    
    Options:

    ``multipart``
        If set to True, the enctype is set to "multipart/form-data".
    ``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.
    
    """
    if multipart:
        options["enctype"] = "multipart/form-data"

    if callable(url):
        url = url()
    else:
        url = html_escape(url)

    method_tag = ""

    if method in ['post', 'get']:
        options['method'] = method
    else:
        options['method'] = "post"
        method_tag = tag('input', type="hidden", name_="_method", value=method)

    options["action"] = url
    return tag("form", True, **options) + method_tag
Beispiel #5
0
def escape_once(html):
    """Escapes a given string without affecting existing escaped entities.

    >>> escape_once("1 < 2 &amp; 3")
    '1 &lt; 2 &amp; 3'
    """
    return fix_double_escape(html_escape(html))
Beispiel #6
0
def form(url, method="post", multipart=False, **options):
    """
    Starts a form tag that points the action to an url. 
    
    The url options should be given either as a string, or as a ``url()``
    function. The method for the form defaults to POST.
    
    Options:

    ``multipart``
        If set to True, the enctype is set to "multipart/form-data".
    ``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.
    
    """
    if multipart:
        options["enctype"] = "multipart/form-data"
    
    if callable(url):
        url = url()
    else:
        url = html_escape(url)
    
    method_tag = ""
    
    if method in ['post', 'get']:
        options['method'] = method
    else:
        options['method'] = "post"
        method_tag = tag('input', type="hidden", name_="_method", value=method)
    
    options["action"] = url
    return tag("form", True, **options) + method_tag
Beispiel #7
0
def escape_once(html):
    """Escapes a given string without affecting existing escaped entities.

    >>> escape_once("1 < 2 &amp; 3")
    '1 &lt; 2 &amp; 3'
    """
    return fix_double_escape(html_escape(html))
Beispiel #8
0
    def install_config_form(self):
        """
        This method will be called to build setup configuration form.
        If this plugin needs parameters, provides form fields here.
        Any html and javascript are welcome.
        """
        if self.get_config(self.key_switch)=="no":
            enable_checked  = ""
            disable_checked = "checked"
        else:
            enable_checked  = "checked"
            disable_checked = ""

        if self.get_config(self.key_debug)=="yes":
            enable_debug = "checked"
            disable_debug = ""
        else:
            enable_debug = ""
            disable_debug = "checked"

        result = ""
        result += "<p><strong>%s</strong></p>" % _("Fill this form")
        result += "<blockquote>"
        result += "<dl>"
        result += "\n<dt>"
        result += _("Enable svn repo mirror: ")
        result += "\n<dd>"
        result += "<input type='radio' name='switch' value='yes' " + \
                enable_checked  + ">" + _("Enable") + "&nbsp;"
        result += "<input type='radio' name='switch' value='no' " + \
                disable_checked + ">" + _("Disable") + "<br>"
        result += "\n<dt>"
        result += _("Svnsync username:"******"\n<dd>"
        result += "<input type='text' name='username' size='18' value='%s'>" % \
                self.get_config(self.key_username)
        result += "\n<dt>"
        result += _("Svnsync password:"******"\n<dd>"
        result += "<input type='password' name='password' size='18' value='%s'>" % \
                self.get_config(self.key_password)
        result += "\n<dt>"
        result += _("Url of downstream svn mirrors:")
        result += "\n<dd>"
        result += "<textarea name='urls' rows='3' cols='40'>"
        result += html_escape( "\n".join( self.get_config(self.key_urls).split(';') ) )
        result += "</textarea>"
        result += "\n<dt>"
        result += _("Debug: ")
        result += "\n<dd>"
        result += "<input type='radio' name='debug' value='yes' " + \
                enable_debug  + ">" + _("Enable") + "&nbsp;"
        result += "<input type='radio' name='debug' value='no' " + \
                disable_debug + ">" + _("Disable") + "<br>"

        result += "\n</dl>"
        result += "</blockquote>"
        return result
Beispiel #9
0
def tag_options(**options):
    strip_unders(options)
    cleaned_options = convert_booleans(dict([(x, y) for x,y in options.iteritems() if y is not None]))
    optionlist = ['%s="%s"' % (x, html_escape(str(y))) for x,y in cleaned_options.iteritems()]
    optionlist.sort()
    if optionlist:
        return ' ' + ' '.join(optionlist)
    else:
        return ''
Beispiel #10
0
    def install_config_form(self):
        """
        This method will be called to build setup configuration form.
        If this plugin needs parameters, provides form fields here.
        Any html and javascript are welcome.
        """
        if self.get_config(self.key_switch)=="no":
            enable_checked  = ""
            disable_checked = "checked"
        else:
            enable_checked  = "checked"
            disable_checked = ""

        result = ""
        result += "<p><strong>%s</strong></p>" % _("Fill this form")
        result += "<blockquote>"
        result += "\n<dl>"
        result += "\n<dt>"
        result += _("Enable trac post commit hook: ")
        result += "\n<dd>"
        result += "<input type='radio' name='switch' value='yes' " + \
                enable_checked  + ">" + _("Enable") + "&nbsp;"
        result += "<input type='radio' name='switch' value='no' " + \
                disable_checked + ">" + _("Disable")
        result += "\n<dt>"
        result += _("Trac environment location: ")
        result += "\n<dd>"
        result += "<input type='text' name='trac_env' size='50' value=\"%s\">" % \
                html_escape(self.get_config(self.key_trac_env))
        result += "\n<dt>"
        result += _("Repository name in trac (default is blank): ")
        result += "\n<dd>"
        result += "<input type='text' name='trac_repos_name' size='20' value=\"%s\">" % \
                html_escape(self.get_config(self.key_trac_repos_name))
        result += "\n<dt>"
        result += _("Fixed ticket status (default is closed): ")
        result += "\n<dd>"
        result += "<input type='text' name='trac_fixed_status' size='10' value=\"%s\">" % \
                html_escape(self.get_config(self.key_trac_fixed_status))
        result += "\n</dl>"
        result += "</blockquote>"
        return result
Beispiel #11
0
    def install_config_form(self):
        """
        This method will be called to build setup configuration form.
        If this plugin needs parameters, provides form fields here.
        Any html and javascript are welcome.
        """
        if self.get_config(self.key_switch) == "no":
            enable_checked = ""
            disable_checked = "checked"
        else:
            enable_checked = "checked"
            disable_checked = ""

        result = ""
        result += "<p><strong>%s</strong></p>" % _("Fill this form")
        result += "<blockquote>"
        result += "\n<dl>"
        result += "\n<dt>"
        result += _("Enable commit log check: ")
        result += "\n<dd>"
        result += "<input type='radio' name='switch' value='yes' " + enable_checked + ">" + _("Enable") + "&nbsp;"
        result += "<input type='radio' name='switch' value='no' " + disable_checked + ">" + _("Disable")
        result += "\n<dt>"
        result += _("Minimal size of commit log: ")
        result += "\n<dd>"
        result += "<input type='text' name='size' size='5' value=\"%s\">" % html_escape(self.get_config(self.key_size))
        result += "\n<dt>"
        result += _("Pattern which commit log must match against: ")
        result += "\n<dd>"
        result += "<textarea name='permit' rows='3' cols='40'>"
        result += html_escape(self.get_config(self.key_permit))
        result += "</textarea>"
        result += "\n<dt>"
        result += _("Pattern which commit log must <b>NOT</b> match against: ")
        result += "\n<dd>"
        result += "<textarea name='prohibit' rows='3' cols='40'>"
        result += html_escape(self.get_config(self.key_prohibit))
        result += "</textarea>"
        result += "\n</dl>"
        result += "</blockquote>"
        return result
Beispiel #12
0
def include(url, default=''):
    """Do a client-side include of ``url``, defaulting to ``default```
        >>> include("/foo","hello")
        '<hx:include src="/foo">hello</hx:include>'
    """
    
    if callable(url):
        url = url()
    else:
        url = html_escape(url)

    return content_tag("hx:include", content=default, src=url)
def include(url, default=''):
    """Do a client-side include of ``url``, defaulting to ``default```
        >>> hinclude.include("/foo","hello")
        '<hx:include src="/foo">hello</hx:include>'
    """
    
    if callable(url):
        url = url()
    else:
        url = html_escape(url)

    return content_tag("hx:include", content=default, src=url)
def tag_options(**options):
    strip_unders(options)
    cleaned_options = convert_booleans(
        dict([(x, y) for x, y in options.iteritems() if y is not None]))
    optionlist = [
        '%s="%s"' % (x, html_escape(str(y)))
        for x, y in cleaned_options.iteritems()
    ]
    optionlist.sort()
    if optionlist:
        return ' ' + ' '.join(optionlist)
    else:
        return ''
Beispiel #15
0
def render_item(item):
    title = item.fn
    if item.urls:
        title = '<a href="%s" class="url fn">%s</a>' % (html(item.urls[0]), title)
    else:
        title = '<span class="fn">%s</span>' % title
    extra_title = []
    if len(item.urls) > 1:
        for url in item.urls[1:]:
            extra_title.append(
                '<a href="%s" class="url">%s</a>' % (
                html(url), html_escape(get_title(url))))
    if extra_title:
        title += ' ' + ' '.join(extra_title)
    # @@: Should do something with photos here
    content = title
    return '<div class="item">%s</div>' % content
Beispiel #16
0
def link_to(name, url='', **html_options):
    """
    Create link tag with text ``name`` and a URL created by the set of ``options``.
    
    See the valid options in the documentation for Routes url_for.
    
    The html_options has three special features. One for creating 
    javascript confirm alerts where if you pass ``confirm='Are you sure?'``, 
    the link will be guarded with a JS popup asking that question. If 
    the user accepts, the link is processed, otherwise not.
    
    Another for creating a popup window, which is done by either passing 
    ``popup`` with True or the options of the window in Javascript form.
    
    And a third for making the link do a POST request (instead of the 
    regular GET) through a dynamically added form element that is 
    instantly submitted. Note that if the user has turned off Javascript, 
    the request will fall back on the GET. So its your responsibility to 
    determine what the action should be once it arrives at the controller. 
    The POST form is turned on by passing ``post`` as True. Note, it's 
    not possible to use POST requests and popup targets at the same time 
    (an exception will be thrown).
    
    Examples::
    
        >> link_to("Delete this page", url(action="destroy", id=4), confirm="Are you sure?")
        >> link_to("Help", url(action="help"), popup=True)
        >> link_to("Busy loop", url(action="busy"), popup=['new_window', 'height=300,width=600'])
        >> link_to("Destroy account", url(action="destroy"), confirm="Are you sure?", method='delete')
        
    """
    if html_options:
        html_options = convert_options_to_javascript(**html_options)
        tag_op = tags.tag_options(**html_options)
    else:
        tag_op = ''
    if callable(url):
        url = url()
    else:
        url = html_escape(url)
    return "<a href=\"%s\"%s>%s</a>" % (url, tag_op, name or url)
Beispiel #17
0
def link_to(name, url='', **html_options):
    """
    Create link tag with text ``name`` and a URL created by the set of ``options``.
    
    See the valid options in the documentation for Routes url_for.
    
    The html_options has three special features. One for creating 
    javascript confirm alerts where if you pass ``confirm='Are you sure?'``, 
    the link will be guarded with a JS popup asking that question. If 
    the user accepts, the link is processed, otherwise not.
    
    Another for creating a popup window, which is done by either passing 
    ``popup`` with True or the options of the window in Javascript form.
    
    And a third for making the link do a POST request (instead of the 
    regular GET) through a dynamically added form element that is 
    instantly submitted. Note that if the user has turned off Javascript, 
    the request will fall back on the GET. So its your responsibility to 
    determine what the action should be once it arrives at the controller. 
    The POST form is turned on by passing ``post`` as True. Note, it's 
    not possible to use POST requests and popup targets at the same time 
    (an exception will be thrown).
    
    Examples::
    
        >> link_to("Delete this page", url(action="destroy", id=4), confirm="Are you sure?")
        >> link_to("Help", url(action="help"), popup=True)
        >> link_to("Busy loop", url(action="busy"), popup=['new_window', 'height=300,width=600'])
        >> link_to("Destroy account", url(action="destroy"), confirm="Are you sure?", method='delete')
        
    """
    if html_options:
        html_options = convert_options_to_javascript(**html_options)
        tag_op = tags.tag_options(**html_options)
    else:
        tag_op = ''
    if callable(url):
        url = url()
    else:
        url = html_escape(url)
    return "<a href=\"%s\"%s>%s</a>" % (url, tag_op, name or url)
Beispiel #18
0
    def start(self, url, method="POST", multipart=False, **options):
        """
        Starts a form tag that points the action to an url.

        The url options should be given either as a string, or as a ``url()``
        function. The method for the form defaults to POST.

        Options:

        ``multipart``
            If set to True, the enctype is set to "multipart/form-data".
        ``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.

        """

        if callable(url):
            url = url()
        else:
            url = html_escape(url)

        return tags.form(url, method, multipart, **options)
Beispiel #19
0
    def start(self, url, method="POST", multipart=False, **options):
        """
        Starts a form tag that points the action to an url.

        The url options should be given either as a string, or as a ``url()``
        function. The method for the form defaults to POST.

        Options:

        ``multipart``
            If set to True, the enctype is set to "multipart/form-data".
        ``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.

        """

        if callable(url):
            url = url()
        else:
            url = html_escape(url)

        return tags.form(url, method, multipart, **options)
Beispiel #20
0
def test_html_escape():
    assert html_escape("foo") == b("foo")
    assert html_escape('<this"that>') == b("&lt;this&quot;that&gt;")
    assert html_escape(u"\u1000") == b("&#4096;")

    class X:
        if PY3:

            def __str__(self):
                return "<\u1000>"

        else:

            def __unicode__(self):
                return u"<\u1000>"

    assert html_escape(X()) == b("&lt;&#4096;&gt;")
    assert html_escape(1) == b("1")
    assert html_escape(None) == ""
def button_to(name, url='', **html_options):
    """
    Generates a form containing a sole button that submits to the
    URL given by ``url``.  
    
    Use this method instead of ``link_to`` for actions that do not have the safe HTTP GET semantics
    implied by using a hypertext link.
    
    The parameters are the same as for ``link_to``.  Any ``html_options`` that you pass will be
    applied to the inner ``input`` element.
    In particular, pass
    
        disabled = True/False
    
    as part of ``html_options`` to control whether the button is
    disabled.  The generated form element is given the class
    'button-to', to which you can attach CSS styles for display
    purposes.
    
    Example 1::
    
        # inside of controller for "feeds"
        >>> button_to("Edit", url(action='edit', id=3))
        <form method="post" action="/feeds/edit/3" class="button-to">
        <div><input value="Edit" type="submit" /></div>
        </form>
    
    Example 2::
    
        >> button_to("Destroy", url(action='destroy', id=3), confirm="Are you sure?")
        <form method="post" action="/feeds/destroy/3" class="button-to">
        <div><input onclick="return confirm('Are you sure?');" value="Destroy" type="submit" />
        </div>
        </form>
    
    *NOTE*: This method generates HTML code that represents a form.
    Forms are "block" content, which means that you should not try to
    insert them into your HTML where only inline content is expected.
    For example, you can legally insert a form inside of a ``div`` or
    ``td`` element or in between ``p`` elements, but not in the middle of
    a run of text, nor can you place a form within another form.
    (Bottom line: Always validate your HTML before going public.)    
    """
    if html_options:
        convert_boolean_attributes(html_options, ['disabled'])

    confirm = html_options.get('confirm')
    if confirm:
        del html_options['confirm']
        html_options['onclick'] = "return %s;" % confirm_javascript_function(
            confirm)

    if callable(url):
        ur = url()
        url, name = ur, name or html_escape(ur)
    else:
        url, name = url, name or url

    html_options.update(dict(type='submit', value=name))

    return """<form method="post" action="%s" class="button-to"><div>""" % html_escape(url) + \
           tags.tag("input", **html_options) + "</div></form>"
Beispiel #22
0
def button_to(name, url='', **html_options):
    """
    Generates a form containing a sole button that submits to the
    URL given by ``url``.  
    
    Use this method instead of ``link_to`` for actions that do not have the safe HTTP GET semantics
    implied by using a hypertext link.
    
    The parameters are the same as for ``link_to``.  Any ``html_options`` that you pass will be
    applied to the inner ``input`` element.
    In particular, pass
    
        disabled = True/False
    
    as part of ``html_options`` to control whether the button is
    disabled.  The generated form element is given the class
    'button-to', to which you can attach CSS styles for display
    purposes.
    
    Example 1::
    
        # inside of controller for "feeds"
        >>> button_to("Edit", url(action='edit', id=3))
        <form method="post" action="/feeds/edit/3" class="button-to">
        <div><input value="Edit" type="submit" /></div>
        </form>
    
    Example 2::
    
        >> button_to("Destroy", url(action='destroy', id=3), confirm="Are you sure?")
        <form method="post" action="/feeds/destroy/3" class="button-to">
        <div><input onclick="return confirm('Are you sure?');" value="Destroy" type="submit" />
        </div>
        </form>
    
    *NOTE*: This method generates HTML code that represents a form.
    Forms are "block" content, which means that you should not try to
    insert them into your HTML where only inline content is expected.
    For example, you can legally insert a form inside of a ``div`` or
    ``td`` element or in between ``p`` elements, but not in the middle of
    a run of text, nor can you place a form within another form.
    (Bottom line: Always validate your HTML before going public.)    
    """
    if html_options:
        convert_boolean_attributes(html_options, ['disabled'])
    
    confirm = html_options.get('confirm')
    if confirm:
        del html_options['confirm']
        html_options['onclick'] = "return %s;" % confirm_javascript_function(confirm)
    
    if callable(url):
        ur = url()
        url, name = ur, name or html_escape(ur)
    else:
        url, name = url, name or url
    
    html_options.update(dict(type='submit', value=name))
    
    return """<form method="post" action="%s" class="button-to"><div>""" % html_escape(url) + \
           tags.tag("input", **html_options) + "</div></form>"
Beispiel #23
0
 def repr(self, obj):
     return util.html_escape(unicode(obj))
Beispiel #24
0
def render_string(s):
    return html_escape(s)
Beispiel #25
0
def render_tag(tag):
    title = html_escape(get_title(tag.url))
    if tag.rating:
        title += ' ' + html(tag.rating)
    return '<a rel="tag" href="%s">%s</a>' % (html_escape(tag.url), title)
Beispiel #26
0
 def repr(self, obj):
     return util.html_escape(unicode(obj))