def __str__(self): if self.static: value = '' for (v,l) in self.options: if v == self.value: value = l return self.as_static(value) options = [] for val, label in self.options: selected = '' if self.value and self.value == val: selected = 'selected="selected"' options.append( '<option value="%s" %s>%s</option>' % (escape(val), selected, escape(label) )) html = literal( input_select_template.format( name = escape(self.name), label = escape(self.label), value = escape(self.value), options = '\n'.join(options), multiple = 'multiple="multiple"' if self.multiple else '', class_label = 'col-md-%d control-label' % self.offset, class_value = 'col-md-%d' % self.size, class_input = 'form-control', extra_control = literal(self.extra_control) if self.extra_control else '', )) return self.div_wrap(html)
def format_data(self, value, show_edit, show_delete, show_view, view_link_class, edit_link_class, delete_link_class): result = literal() if self.edit_endpoint and show_edit: result += link_to( literal(' '), flask.url_for(self.edit_endpoint, objid=value, session_key=self.grid.session_key), **{ 'aria-label': _('Edit'), 'class_': edit_link_class, 'title': _('Edit') } ) if self.delete_endpoint and show_delete: result += link_to( literal(' '), flask.url_for(self.delete_endpoint, objid=value, session_key=self.grid.session_key), **{ 'aria-label': _('Delete'), 'class_': delete_link_class, 'title': _('Delete') } ) if self.view_endpoint and show_view: result += link_to( literal(' '), flask.url_for(self.view_endpoint, objid=value, session_key=self.grid.session_key), **{ 'aria-label': _('View'), 'class_': view_link_class, 'title': _('View') } ) return result
def new(self): """ create new model object """ schema = self.context.schema.bind(db_session=self.context.db_session) form = Form(schema, buttons=('add',)) resources = form.get_widget_resources() js_resources = resources['js'] css_resources = resources['css'] js_links = [self.request.static_url(r) for r in js_resources] css_links = [self.request.static_url(r) for r in css_resources] js_tags = [literal('<script type="text/javascript" src="%s"></script>' % link) for link in js_links] css_tags = [literal('<link rel="stylesheet" href="%s"/>' % link) for link in css_links] resource_tags = js_tags + css_tags if self.request.method == 'POST': controls = self.request.params.items() try: params = form.validate(controls) item = self.context.add(params) del self.request.matchdict['traverse'] location = self.request.resource_url( self.context, route_name=self.request.matched_route.name, route_kw=self.request.matchdict) return HTTPFound(location=location) except ValidationFailure as e: return dict(form=e.render(), resource_tags=resource_tags) return dict(form=form.render(), resource_tags=resource_tags)
def test_lit_re(): lit = literal('This is a <string>') unlit = 'This is also a <string>' result = lit_sub(r'<str', literal('<b'), lit) eq_(u'This is a <bing>', escape(result)) result = lit_sub(r'a <str', 'a <b> <b', unlit) eq_(u'This is also a <b> <bing>', escape(result))
def test_lit_sub(self): lit = literal("This is a <string>") unlit = "This is also a <string>" result = lit_sub(r"<str", literal("<b"), lit) assert "This is a <bing>" == escape(result) result = lit_sub(r"a <str", "a <b> <b", unlit) assert "This is also a <b> <bing>" == escape(result)
def test_literal_dict(): lit = literal(u'This string <>') unq = 'This has <crap>' sub = literal('%s and %s') eq_(u'This string <> and This has <crap>', sub % (lit, unq)) sub = literal('%(lit)s and %(lit)r') eq_(u"This string <> and literal(u'This string <>')", sub % dict(lit=lit)) sub = literal('%(unq)r and %(unq)s') eq_(u"'This has <crap>' and This has <crap>", sub % dict(unq=unq))
def render_body(self, request): if self.body_format == 'html': return literal(self.body) elif self.body_format == 'md': photos = self.photos return literal(markdown( self.body, extensions=[ImageSetExtension(request, photos)])) else: return self.body
def render_static(self, **kwargs): self.set_attrs(**kwargs) if self.chosen or self.get_attr(self.chosen_attr, None): if self.displayval or self.displayval == 0: todisplay = self.displayval else: todisplay = literal(' ') else: todisplay = literal(' ') return HTML.span(todisplay, **self._static_attributes())
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.tag("a", text, **a_options) + literal(after)
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)
def label(value, **kwargs): """ Return a label tag >>> print(label('My label', for_='fieldname')) <label for="fieldname">My label</label> """ if 'for_' in kwargs: kwargs['for'] = kwargs.pop('for_') return tag('label', open=True, **kwargs) + literal(value) + literal('</label>')
def label(value, **kwargs): """ Return a label tag >>> print(label('My label', for_='fieldname')) <label for="fieldname">My label</label> """ if "for_" in kwargs: kwargs["for"] = kwargs.pop("for_") return tag("label", open=True, **kwargs) + literal(value) + literal("</label>")
def label(value, **kwargs): """ Return a label tag >>> print(label('My label', for_='fieldname')) <label for="fieldname">My label</label> """ if 'for_' in kwargs: kwargs['for'] = kwargs.pop('for_') return tag('label', open=True, ** kwargs) + literal(value) + literal('</label>')
def test_literal(): lit = literal(u'This string <>') other = literal(u'<other>') eq_(u'This string <><other>', lit + other) assert type(lit + other) is literal eq_(u'"<other>', '"' + other) eq_(u'<other>"', other + '"') mod = literal('<%s>ello') eq_(u'<<H>>ello', mod % '<H>') assert type(mod % '<H>') is literal eq_(HTML('<a>'), '<a>') assert type(HTML('<a>')) is literal
def test_literal(self): lit = literal("This string <>") other = literal("<other>") assert "This string <><other>" == lit + other assert type(lit + other) is literal assert ""<other>" == '"' + other assert "<other>"" == other + '"' mod = literal("<%s>ello") assert "<<H>>ello" == mod % "<H>" assert type(mod % "<H>") is literal assert HTML("<a>") == "<a>" assert type(HTML("<a>")) is literal
def __str__(self): if type(self.size) == str and 'x' in self.size: rows,size = ( int(v) for v in self.size.split('x') ) else: rows,size = 4, self.size return literal( input_textarea_template.format( name=escape(self.name), label=escape(self.label), value=escape(self.value), class_div = 'form-group', class_label = 'col-md-%d control-label' % self.offset, class_value = 'col-md-%d' % size, rows = rows, class_input = 'form-control', extra_control = literal(self.extra_control) if self.extra_control else '', style = 'style="font-family:monospace;"' ) )
def test_literal_dict(self): lit = literal("This string <>") unq = "This has <crap>" sub = literal("%s and %s") assert "This string <> and This has <crap>", sub % (lit == unq) sub = literal("%(lit)s and %(lit)r") b = "This string <> and literal(u'This string <>')" if six.PY3: b = b.replace( "(u", "(" ) # Delete 'u' string prefix. assert sub % dict(lit=lit) == b sub = literal("%(unq)r and %(unq)s") b = "u'This has <crap>' and This has <crap>" if six.PY3: b = b[1:] # Delete 'u' string prefix. assert sub % dict(unq=unq) == b
def table_column_headings(self): headings = [] for col in self.grid.iter_columns('html'): headings.append(self.table_th(col)) th_str = '\n'.join(headings) th_str = reindent(th_str, 12) return literal(th_str)
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)
def auto_link(text, link="all", **href_attrs): """ Turn all urls and email addresses into clickable links. ``link`` Used to determine what to link. Options are "all", "email_addresses", or "urls" ``href_attrs`` Additional attributes for generated <a> tags. Example:: >>> auto_link("Go to http://www.planetpython.com and say hello to [email protected]") literal(u'Go to <a href="http://www.planetpython.com">http://www.planetpython.com</a> and say hello to <a href="mailto:[email protected]">[email protected]</a>') """ if not text: return literal("") text = escape(text) if link == "all": return _auto_link_urls(_auto_link_email_addresses(text), **href_attrs) elif link == "email_addresses": return _auto_link_email_addresses(text) else: return _auto_link_urls(text, **href_attrs)
def gravatar(email_address, cls='', size=30): """return html element of the gravatar This method will return an <img> with the resolution double the size (for retina screens) of the image. If the url returned from gravatar_url is empty then we fallback to using an icon. """ from tg import tmpl_context as c if not c.visual.use_gravatar: return '' src = gravatar_url(email_address, size * 2) if src: # here it makes sense to use style="width: ..." (instead of, say, a # stylesheet) because we using this to generate a high-res (retina) size html = ('<i class="icon-gravatar {cls}"' ' style="font-size: {size}px;background-size: {size}px;background-image: url(\'{src}\')"' '></i>').format(cls=cls, size=size, src=src) else: # if src is empty then there was no gravatar, so we use a font icon html = ("""<i class="icon-user {cls}" style="font-size: {size}px;"></i>""" .format(cls=cls, size=size, src=src)) return literal(html)
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(' '))) 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)
def render_static(self): self.add_attr('class', 'textarea') if self.displayval == '': todisplay = literal(' ') else: todisplay = self.displayval return HTML.span(todisplay, **self._static_attributes())
def renderResource(request, library_name, resource_type, resource_id): # pragma: no cover """ This function will inject a resource from Jinja2 using the jsresource or cssresource tags. Not in Coverage because Coverage cannot track them from Jinja2 :param request: :param library_name: :param resource_type: :param resource_id: :return: """ if resource_type == "JS" or resource_type == "CSS": if resource_type == "CSS": html = '<link href="{{ file }}" rel="stylesheet">' else: html = '<script src="{{ file }}"></script>' resources = r.need(library_name, resource_id, resource_type) resources_to_include = [] for resource in resources: if not request.activeResources.resourceInRequest( library_name, resource["resourceID"], resource_type): request.activeResources.addResource(library_name, resource["resourceID"], resource_type) resources_to_include.append( jinjaEnv.from_string(html).render( file=request.application_url + "/" + resource["filePath"])) return literal("\n".join(resources_to_include)) else: return ""
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)
def test_hidden_fields_from_dict(self): tag = form("/submit", hidden_fields={'foo': 'bar'}) assert tag == literal( '<form action="/submit" method="post">' '<div style="display:none">\n' '<input name="foo" type="hidden" value="bar" />\n' '</div>\n')
def test1(self): opts = self.get_currency_options() a = select("currency", "$", opts) b = literal( '<select id="currency" name="currency">\n<option selected="selected" value="$">Dollar</option>\n<option value="DKK">Kroner</option>\n</select>' ) self.check(a, b)
def auto_link(text, link="all", **href_attrs): """ Turn all urls and email addresses into clickable links. ``link`` Used to determine what to link. Options are "all", "email_addresses", or "urls" ``href_attrs`` Additional attributes for generated <a> tags. Example:: >>> auto_link("Go to http://www.planetpython.com and say hello to [email protected]") literal(u'Go to <a href="http://www.planetpython.com">http://www.planetpython.com</a> and say hello to <a href="mailto:[email protected]">[email protected]</a>') """ if not text: return literal(u"") text = escape(text) if link == "all": return _auto_link_urls(_auto_link_email_addresses(text), **href_attrs) elif link == "email_addresses": return _auto_link_email_addresses(text) else: return _auto_link_urls(text, **href_attrs)
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)
def test3(self): a = select("cc", ["VISA", "Discover"], ["VISA", "MasterCard", "Discover"]) b = literal( '<select id="cc" name="cc">\n<option selected="selected">VISA</option>\n<option>MasterCard</option>\n<option selected="selected">Discover</option>\n</select>' ) self.check(a, b)
def test_html(self): opts = self.get_options() a = opts.render() b = literal( '<option>A</option>\n<option>1</option>\n<option value="b">B</option>\n' ) self.check(a, b)
def js(value): """Convert Python value to the corresponding JavaScript representation. This is necessary to safely insert arbitrary values into HTML <script> sections e.g. using Mako template expression substitution. Note: Rather than using this function, it's preferable to avoid the insertion of values into HTML <script> sections altogether. Instead, data should (to the extent possible) be passed to JavaScript using data attributes or AJAX calls, eliminating the need for JS specific escaping. Note: This is not safe for use in attributes (e.g. onclick), because quotes are not escaped. Because the rules for parsing <script> varies between XHTML (where normal rules apply for any special characters) and HTML (where entities are not interpreted, but the literal string "</script>" is forbidden), the function ensures that the result never contains '&', '<' and '>', thus making it safe in both those contexts (but not in attributes). """ return literal( ('(' + json.dumps(value) + ')') # In JSON, the following can only appear in string literals. .replace('&', r'\x26') .replace('<', r'\x3c') .replace('>', r'\x3e') )
def test7(self): opts = [Option("No", False), Option("Yes", True)] a = select("enabled", True, opts) b = literal( '<select id="enabled" name="enabled">\n<option value="False">No</option>\n<option selected="selected" value="True">Yes</option>\n</select>' ) self.check(a, b)
def test4(self): opts = self.get_currency_options() a = select("currency", None, opts, prompt="Please choose ...") b = literal( '<select id="currency" name="currency">\n<option selected="selected" value="">Please choose ...</option>\n<option value="$">Dollar</option>\n<option value="DKK">Kroner</option>\n</select>' ) self.check(a, b)
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)
def test_stylesheet_link_tag(self): eq_(literal(u'<link href="/dir/file.css" media="all" rel="stylesheet" type="text/css" />'), stylesheet_link('/dir/file.css', media='all')) eq_('<link href="style.css" media="all" rel="stylesheet" type="text/css" />', stylesheet_link('style.css', media='all')) eq_('<link href="/random.styles" media="screen" rel="stylesheet" type="text/css" />\n<link href="/css/stylish.css" media="screen" rel="stylesheet" type="text/css" />', stylesheet_link('/random.styles', '/css/stylish.css'))
def sorting_select_options(self): options = [tags.Option(literal(' '), value='')] for col in self.grid.columns: if col.can_sort: options.append(tags.Option(col.label, value=col.key)) options.append(tags.Option(_('{label} DESC', label=col.label), value='-' + col.key)) return options
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)
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
def _legacy_highlight(text, phrase, highlighter, flags): """WebHelpers 0.6 style highlight with deprecated ``highlighter arg.""" warnings.warn("the ``highlighter`` argument is deprecated", DeprecationWarning) pat = "(%s)" % re.escape(phrase) rx = re.compile(pat, flags) highlighter = literal(highlighter) return lit_sub(rx, highlighter, text)
def __str__(self): return literal( checkboxes_template.format( class_div = 'form-group', class_label = 'col-md-3 control-label', class_value = 'col-md-8', label = self.label, boxes = '\n'.join( str(item) for item in self.contents ) ))
def test_html_selected(self): selected_values = [1] opts = self.get_options() a = opts.render(selected_values) b = literal( '<option>A</option>\n<option selected="selected">1</option>\n<option value="b">B</option>\n' ) self.check(a, b)
def as_static(self, value=None): return literal( input_static_template.format( name=escape(self.name), label=escape(self.label), value=escape(value or self.value), class_div = 'form-group' + (' has-error' if self.error else ''), class_label = 'col-md-%d control-label' % self.offset, class_value = 'col-md-%d' % self.size, class_input = 'form-control', ) )
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)
def filtering_col_op_select_options(self, filter): options = [tags.Option(literal(' '), value='')] for op in filter.operators: options.append(tags.Option( self.filtering_operator_labels.get(op.key, op.display), value=op.key, )) return options
def pager(self): return literal( paginate.Page.pager(self, format='<ul class="pagination">$link_previous\n~4~$link_next</ul>', link_attr={'class': 'pager_link'}, dotdot_attr={'class': 'pager_dotdot'}, separator='\n', ))
def render_w_mentions(source, repo_name=None): """ Render plain text with revision hashes and issue references urlified and with @mention highlighting. """ s = safe_str(source) s = urlify_text(s, repo_name=repo_name) return literal('<div class="formatted-fixed">%s</div>' % s)
def test2(self): a = select("cc", "MasterCard", ["VISA", "MasterCard"], id="cc", class_="blue") b = literal( '<select class="blue" id="cc" name="cc">\n<option>VISA</option>\n<option selected="selected">MasterCard</option>\n</select>' ) self.check(a, b)
def render_static(self): if self.etype in ('button', 'file', 'hidden', 'image', 'submit', 'reset', 'password'): return '' if self.displayval == '': todisplay = literal(' ') else: todisplay = self.displayval return HTML.span(todisplay, **self._static_attributes())
def render_static(self): if self.displayval == '': todisplay = literal(' ') 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())
def pygmentize(filenode, **kwargs): """ pygmentize function using pygments :param filenode: """ lexer = get_custom_lexer(filenode.extension) or filenode.lexer return literal(markup_whitespace( code_highlight(safe_str(filenode.content), lexer, CodeHtmlFormatter(**kwargs))))
def test3(self): sort = "name" a = th_sortable(sort, "date", "Date", None, link_attrs={"onclick": "myfunc()"}) b = literal('<th><a onclick="myfunc()">Date</a></th>') self.check(a, b)
def end_form(): """Output "</form>". Example:: >>> end_form() literal(u'</form>') """ return literal("</form>")
def action_parser_icon(): action = user_log.action action_params = None x = action.split(':') if len(x) > 1: action, action_params = x ico = action_map.get(action, ['', '', ''])[2] html = """<i class="%s"></i>""" % ico return literal(html)