def formaturl(url, title=None): if not url: return '' if title is None: title = url parsed = urlparse(url) if parsed.scheme == 'http' or parsed.scheme == 'https': url = Markup.escape(url) title = Markup.escape(title) title = unicode(title).replace('*', '<span class="censored">*</span>').replace(u'…', u'<span class="censored">…</span>') return Markup('<a href="%(url)s">%(title)s</a>' % {'url': url, 'title': title}) else: return url
def formatBugLinks(value): def addLink(match): linkApp = match.group(1) if linkApp != None: linkApp = linkApp.lower() linkType = match.group(2).lower() linkNum = int(match.group(3)) if linkType == 'topic': link = 'https://adblockplus.org/forum/viewtopic.php?t=%i' % linkNum elif linkApp == None and linkType == 'issue': link = 'https://issues.adblockplus.org/ticket/%i' % linkNum elif linkApp == 'webkit': link = 'https://bugs.webkit.org/show_bug.cgi?id=%i' % linkNum elif linkApp != None: link = 'http://code.google.com/p/chromium/issues/detail?id=%i' % linkNum else: link = 'https://bugzilla.mozilla.org/show_bug.cgi?id=%i' % linkNum return '<a href="%s">%s</a>' % (link, match.group(0)) regexp = re.compile(r'(https?://\S+?)([.,:;!?"\']?(?:\s|$))', re.I | re.U) regexp2 = re.compile(r'(?:\b(WebKit|Chrome|Chromium)\s+)?\b(bug|issue|topic)\s+(\d+)', re.I | re.U) value = unicode(Markup.escape(value)) value = re.sub(regexp, r'<a href="\1">\1</a>\2', value); value = re.sub(regexp2, addLink, value) return Markup(value)
def do_indent( s, width=4, first=False, blank=False, indentfirst=None ): """Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default. :param width: Number of spaces to indent by. :param first: Don't skip indenting the first line. :param blank: Don't skip indenting empty lines. .. versionchanged:: 2.10 Blank lines are not indented by default. Rename the ``indentfirst`` argument to ``first``. """ if indentfirst is not None: warnings.warn(DeprecationWarning( 'The "indentfirst" argument is renamed to "first".' ), stacklevel=2) first = indentfirst indention = u' ' * width newline = u'\n' if isinstance(s, Markup): indention = Markup(indention) newline = Markup(newline) s += newline # this quirk is necessary for splitlines method if blank: rv = (newline + indention).join(s.splitlines()) else: lines = s.splitlines() rv = lines.pop(0) if lines: rv += newline + newline.join( indention + line if line else line for line in lines ) if first: rv = indention + rv return rv
def __init__(self, product_id, sql_conn): self.sql_conn = sql_conn self.product = sql_conn.get_product_by_id(product_id)[0] self.has_options = False try: self.product['manufacturer_name'] = sql_conn.get_manufacturer_by_id(self.product['manufacturer_id'])[0][ 'name'] except: self.product['manufacturer_name'] = "None" self.product['categories'] = [a['name'] for a in self.sql_conn.get_categories_by_product_id(product_id)] self.product['display_description'] = Markup.unescape(Markup(self.product['display_description'])) if self.sql_conn.has_product_options(product_id): self.has_options = True self.options = self.sql_conn.get_options_by_product(product_id) self.option_number = len(self.options) self.product['has_options'] = True else: self.options = dict() self.options['product_option_id'] = 0 self.options['option_value_id'] = 0 self.product['has_options'] = False self.product['options'] = self.options
def ngettext(__context, __singular, __plural, __num, **variables): variables.setdefault('num', __num) rv = __context.call(func, __singular, __plural, __num) if __context.eval_ctx.autoescape: rv = Markup(rv) return rv % variables
def sql_safe(value): """Filter to mark the value of an expression as safe for inserting in a SQL statement""" return Markup(value)
def __call__(self): rv = concat(self._stack[self._depth](self._context)) if self._context.eval_ctx.autoescape: rv = Markup(rv) return rv
def __html__(self): return Markup(concat(self._body_stream))
def _invoke(self, arguments, autoescape): """This method is being swapped out by the async implementation.""" rv = self._func(*arguments) if autoescape: rv = Markup(rv) return rv
async def async_call(self): rv = await concat_async(self._stack[self._depth](self._context)) if self._context.eval_ctx.autoescape: rv = Markup(rv) return rv
def boolean_to_icon(inp): template = '<span class="glyphicon glyphicon-%s-sign text-%s" aria-hidden="true"></span>' if inp: return Markup(template % ('ok', 'success')) return Markup(template % ('remove', 'danger'))
def formatnewlines(value): value = Markup.escape(value) value = unicode(value).replace('\n', '<br />') return Markup(value)
def html(self): return Markup(self.render())
def json(o): """Dump an object to json.""" return Markup(encoder.dumps(o))
def _urlencode(self, s): if type(s) == 'Markup': s = s.unescape() return Markup(urllib.quote_plus(s.encode('utf-8')))
def do_mark_safe(value): return Markup(value)
def embed_html(self): return Markup(build_video_embed(self.value))
def as_const(self): return Markup(self.expr.as_const())
def markdown_filter(source): from ckan.lib.helpers import markdown return Markup(markdown(bleach.clean(source)))
def __call__(self, *args, **kwargs): # This requires a bit of explanation, In the past we used to # decide largely based on compile-time information if a macro is # safe or unsafe. While there was a volatile mode it was largely # unused for deciding on escaping. This turns out to be # problemtic for macros because if a macro is safe or not not so # much depends on the escape mode when it was defined but when it # was used. # # Because however we export macros from the module system and # there are historic callers that do not pass an eval context (and # will continue to not pass one), we need to perform an instance # check here. # # This is considered safe because an eval context is not a valid # argument to callables otherwise anwyays. Worst case here is # that if no eval context is passed we fall back to the compile # time autoescape flag. if args and isinstance(args[0], EvalContext): autoescape = args[0].autoescape args = args[1:] else: autoescape = self._default_autoescape # try to consume the positional arguments arguments = list(args[:self._argument_count]) off = len(arguments) # For information why this is necessary refer to the handling # of caller in the `macro_body` handler in the compiler. found_caller = False # if the number of arguments consumed is not the number of # arguments expected we start filling in keyword arguments # and defaults. if off != self._argument_count: for idx, name in enumerate(self.arguments[len(arguments):]): try: value = kwargs.pop(name) except KeyError: value = missing if name == 'caller': found_caller = True arguments.append(value) else: found_caller = self.explicit_caller # it's important that the order of these arguments does not change # if not also changed in the compiler's `function_scoping` method. # the order is caller, keyword arguments, positional arguments! if self.caller and not found_caller: caller = kwargs.pop('caller', None) if caller is None: caller = self._environment.undefined('No caller defined', name='caller') arguments.append(caller) if self.catch_kwargs: arguments.append(kwargs) elif kwargs: if 'caller' in kwargs: raise TypeError('macro %r was invoked with two values for ' 'the special caller argument. This is ' 'most likely a bug.' % self.name) raise TypeError('macro %r takes no keyword argument %r' % (self.name, next(iter(kwargs)))) if self.catch_varargs: arguments.append(args[self._argument_count:]) elif len(args) > self._argument_count: raise TypeError('macro %r takes not more than %d argument(s)' % (self.name, len(self.arguments))) rv = self._func(*arguments) if autoescape: rv = Markup(rv) return rv
def avatar(user, size=100): url = ('{0}/u/{1}/avatar/{2}/' if size else '{0}/u/{1}/avatar/').format(conf['sso_url'], user.name, size) return Markup('<img src="{0}" class="gravatar" width="{1}" height="{1}"/>'.format(url, size))
def as_const(self, eval_ctx=None): eval_ctx = get_eval_context(self, eval_ctx) return Markup(self.expr.as_const(eval_ctx))
{%- endfor %}""") assert tmpl.render(articles=articles).split("|") == [ "1970[aha][interesting][really?]", "1971[totally not]", "", ] @mark_dualiter("int_items", lambda: [1, 2, 3]) def test_join_env_int(env_async, int_items): tmpl = env_async.from_string('{{ items()|join("|") }}') out = tmpl.render(items=int_items) assert out == "1|2|3" @mark_dualiter("string_items", lambda: ["<foo>", Markup("<span>foo</span>")]) def test_join_string_list(string_items): env2 = Environment(autoescape=True, enable_async=True) tmpl = env2.from_string('{{ ["<foo>", "<span>foo</span>"|safe]|join }}') assert tmpl.render(items=string_items) == "<foo><span>foo</span>" def make_users(): User = namedtuple("User", "username") return map(User, ["foo", "bar"]) @mark_dualiter("users", make_users) def test_join_attribute(env_async, users): tmpl = env_async.from_string("""{{ users()|join(', ', 'username') }}""") assert tmpl.render(users=users) == "foo, bar"
def showfor_data(products): # Markup() marks this data as safe. return Markup(jsonlib.dumps(_showfor_data(products)))
def href(value, link): return Markup( soft_unicode("<br>".join([ "<a href=/" + link + "/" + x + " target=_blank>" + x + "</a>" for x in value ])))
def do_mark_safe(value): """Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped. """ return Markup(value)
shard.width = appstruct['width'] shard.height = appstruct['height'] shard.triggers = appstruct['triggers'] except ValidationFailure, e: return {'form': Markup(e.render())} appstruct = dict( name=shard.name, url=shard.url, selector=shard.selector, width=shard.width, height=shard.height, triggers=shard.triggers, ) return { 'form': Markup(shardform.render(appstruct)), 'shard': u'%s/shards/%d/preview' % (request.application_url, shard.id), 'shard_full': u'%s/shards/%d' % (request.application_url, shard.id), 'title': 'Edit Shard' } def new_shard(request): shardform = Form(schema.Shard(), buttons=('submit', )) if 'submit' in request.POST: controls = request.POST.items() try: appstruct = shardform.validate(controls) newshard = tables.Shard( name=appstruct['name'], url=appstruct['url'],
def gettext(__context, __string, **variables): rv = __context.call(func, __string) if __context.eval_ctx.autoescape: rv = Markup(rv) return rv % variables
def do_striptags(value): """Strip SGML/XML tags and replace adjacent whitespace by one space. """ if hasattr(value, '__html__'): value = value.__html__() return Markup(text_type(value)).striptags()
def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False): rv = urlize(value, trim_url_limit, nofollow) if eval_ctx.autoescape: rv = Markup(rv) return rv
async def async_invoke(self, arguments, autoescape): rv = await self._func(*arguments) if autoescape: rv = Markup(rv) return rv
def do_striptags(value): if hasattr(value, '__html__'): value = value.__html__() return Markup(unicode(value)).striptags()
def as_const(self): if self.environment.autoescape: return Markup(self.data) return self.data
def get_context(self): if self.context is None: self.context = super(Page, self).get_context() self.context['content'] = Markup(self.get_html_content()) self.context['raw_content'] = self.content return self.context