def format_address(this, address, include_phone=True, inline=False, latin=False): address["name"] = f"{address.get('first_name', '')} {address.get('last_name', '')}" address["country_code"] = address["country"] address[ "street_address" ] = f"{address.get('street_address_1','')}\n {address.get('street_address_2','')}" address_lines = i18naddress.format_address(address, latin).split("\n") phone = address.get("phone") if include_phone and phone: address_lines.append(str(phone)) if inline is True: return pybars.strlist([", ".join(address_lines)]) return pybars.strlist(["<br>".join(address_lines)])
def title(this, *values): """ Pybars helper for setting the page title """ values = [html.escape(value) for value in values if value not in ['', None]] return pybars.strlist("{{title}}" + " - ".join(values) + "{{/title}}")
def helper_nl2br(self, this, *args, **kwargs): """ var nl2br = (text + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '<br>' + '$2'); return new Handlebars.SafeString(nl2br); """ result = re.sub(r'([^>\r\n]?)(\r\n|\n\r|\r|\n)', '<br/>', args[0]) return strlist(result)
def user_profile_image(template_name, pad, scope, *args, **kwargs): size = 144 if len(args) == 1 and isinstance(size, (basestring, int)): size = int(args[0]) screen_name = scope.get('screen_name') name = scope.get('name') alt = "" if size > 72: alt = "@%s" % screen_name if name is not None: alt = "%s (%s)" % (name, alt) alt = 'alt="%s" ' % alt screen_name = screen_name.lower() url = scope.get('image_url', None) try: if url is None: ts = scope.get('timestamp', {}).get('image_cache', None) url = api.HTTPSchemas._profileImageURL(screen_name, ts, size) except Exception: pass if url is None: url = "http://static.stamped.com/users/%s-%sx%s.jpg" % (screen_name, size, size) #if not url.endswith('default.jpg'): # url = "http://static.stamped.com/users/%s-%sx%s.jpg" % (screen_name, size, size) return pybars.strlist('<img %s src="%s" />' % (alt, url))
def join(this, values, separator): """ Pybars helper for joining an array of values """ values = [html.escape(str(value)) for value in values] return pybars.strlist(separator.join(values))
def goodbyes(this, options): result = strlist() for bye in ["Goodbye", "goodbye", "GOODBYE"]: result.grow(bye) result.grow(' ') result.grow(options['fn'](this)) result.grow("! ") return result
def highlight(this, string): """ Pybars helper to convert highlighting characters (\x02 and \x03) into bold HTML tags """ string = html.escape(string).replace("\x02", '<b>').replace("\x03", '</b>') return pybars.strlist(string)
def test_block_helper_staying_in_the_same_context(self): template = u"{{#form}}<p>{{name}}</p>{{/form}}" helpers = { 'form': lambda this, options: strlist( [u"<form>", options['fn'](this), u"</form>"]) } self.assertEqual("<form><p>Yehuda</p></form>", render(template, {'name': "Yehuda"}, helpers=helpers))
def title(this, *values): """ Pybars helper for setting the page title """ values = [ html.escape(value) for value in values if value not in ['', None] ] return pybars.strlist("{{title}}" + " - ".join(values) + "{{/title}}")
def url_abbr(this, url, domain_only=False): """ Pybars helper for generating the abbreviation of a URL """ output = pybars.strlist() output.append('<a href="%s" title="%s">' % (html.escape(url), html.escape(url))) collapsableUrl = re.sub('^https?://(www\.)?', '', url) if domain_only: collapsableUrl = re.sub('/.*$', '', collapsableUrl) collapsableUrl = html.escape(collapsableUrl) collapsableUrl = collapsableUrl.replace('/', u"/\u200B") collapsableUrl = collapsableUrl.replace('.', u".\u200B") output.append(collapsableUrl) output.append('</a>') return output
def price(this, net_amount, gross_amount, currency, display_gross=False): amount = net_amount if display_gross: amount = gross_amount try: value = Decimal(amount) except (TypeError, InvalidOperation): return "" locale, locale_code = get_locale_data() pattern = locale.currency_formats.get("standard").pattern pattern = re.sub("(\xa4+)", '<span class="currency">\\1</span>', pattern) formatted_price = format_currency( value, currency, format=pattern, locale=locale_code ) return pybars.strlist([formatted_price])
def _each_sorted(this, options, context, reverse=False): """ A version of the each helper where dicts' keys are sorted """ if not context: return options['inverse'](this) cond_reversed = reversed if reverse else (lambda x: x) result = strlist() if is_dictlike(context): for key, local_context in cond_reversed(sorted(context.items())): result.grow(options['fn'](local_context, key=key)) elif is_iterable(context): for index, local_context in enumerate(context): result.grow(options['fn'](local_context, index=index)) else: return options['inverse'](this) return result
def entity_image(template_name, pad, scope, *args, **kwargs): size = None if len(args) == 1 and isinstance(size, (basestring, int)): size = int(args[0]) alt = scope.get('title', "") url = None large = None width = -1 images = scope.get('images') if images is not None: for multires_image in images: for sized_image in multires_image['sizes']: if (size is None and url is None) or ('width' in sized_image and sized_image['width'] == size): url = sized_image['url'] if large is None or (width is not None and 'width' in sized_image and sized_image['width'] > width): large = sized_image['url'] width = sized_image.get('width', None) if url is not None: break if url is None: for multires_image in images: for sized_image in multires_image['sizes']: url = sized_image['url'] break if url is not None: break if url is None: return "" onerror = "this.className='hidden'; if (typeof(window.g_update_stamps) !== 'undefined') { g_update_stamps(); }" pre = '<div class="entity-image-wrapper"><img alt="%s" src="%s" onerror="%s" />' % (alt, url, onerror) body = '<a class="lightbox zoom" href="%s"></a></div>' % large return pybars.strlist(pre + "\n" + body)
def json(this, data): """ Pybars helper for generating raw JSON """ return pybars.strlist(json_.dumps(data))
def link_to(this, helpername, context): if helpername == 'link_to': return strlist(("<a>", context, "</a>"))
def test_constructing_a_safestring_from_a_string_and_checking_its_type( self): reference = "testing 1, 2, 3" instance = strlist([reference]) self.assertIsInstance(instance, strlist) self.assertEqual(str_class(reference), str_class(instance))
def link(this, options): return strlist(('<a href="/people/', str_class(this['id']), '">', options['fn'](this), '</a>'))
def json(this, data): """ Pybars helper for generating raw JSON """ return pybars.strlist( json_.dumps(data) )
def goodbye(this, options): return strlist([this['goodbye'].upper()]) + options['fn'](this)
def test_constructing_a_safestring_from_a_string_and_checking_its_type(self): reference = "testing 1, 2, 3" instance = strlist([reference]) self.assertIsInstance(instance, strlist) self.assertEqual(str_class(reference), str_class(instance))
def _quoted(this, value): if value: return strlist( ['"', value.replace('\\', '\\\\').replace('"', '\\"'), '"'])
def test_functions_returning_safestrings(self): # Note that we use liststr for our safestring implementation. text = '&\"\\<>' self.assertEqual( text, render(u'{{awesome}}', {'awesome': lambda this: strlist([text])}))
def test_block_helper_staying_in_the_same_context(self): template = u"{{#form}}<p>{{name}}</p>{{/form}}" helpers = {'form': lambda this, options: strlist([u"<form>", options['fn'](this), u"</form>"])} self.assertEqual("<form><p>Yehuda</p></form>", render(template, {'name': "Yehuda"}, helpers=helpers))
def test_functions_returning_safestrings(self): # Note that we use liststr for our safestring implementation. text = '&\"\\<>' self.assertEqual(text, render(u'{{awesome}}', {'awesome': lambda this: strlist([text])}))