Ejemplo n.º 1
0
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)])
Ejemplo n.º 2
0
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}}")
Ejemplo n.º 3
0
 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)
Ejemplo n.º 4
0
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))
Ejemplo n.º 5
0
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))
Ejemplo n.º 6
0
 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
Ejemplo n.º 7
0
 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
Ejemplo n.º 8
0
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)
Ejemplo n.º 9
0
 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))
Ejemplo n.º 10
0
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}}")
Ejemplo n.º 11
0
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
Ejemplo n.º 12
0
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
Ejemplo n.º 13
0
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])
Ejemplo n.º 14
0
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
Ejemplo n.º 15
0
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)
Ejemplo n.º 16
0
def json(this, data):
    """
    Pybars helper for generating raw JSON
    """

    return pybars.strlist(json_.dumps(data))
Ejemplo n.º 17
0
 def link_to(this, helpername, context):
     if helpername == 'link_to':
         return strlist(("<a>", context, "</a>"))
Ejemplo n.º 18
0
 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))
Ejemplo n.º 19
0
 def link(this, options):
     return strlist(('<a href="/people/', str_class(this['id']), '">',
                     options['fn'](this), '</a>'))
Ejemplo n.º 20
0
def json(this, data):
    """
    Pybars helper for generating raw JSON
    """

    return pybars.strlist( json_.dumps(data) )
Ejemplo n.º 21
0
 def goodbye(this, options):
     return strlist([this['goodbye'].upper()]) + options['fn'](this)
Ejemplo n.º 22
0
 def goodbye(this, options):
     return strlist([this['goodbye'].upper()]) + options['fn'](this)
Ejemplo n.º 23
0
 def link_to(this, helpername, context):
     if helpername == 'link_to':
         return strlist(("<a>", context, "</a>"))
Ejemplo n.º 24
0
 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))
Ejemplo n.º 25
0
 def link(this, options):
     return strlist(('<a href="/people/', str_class(this['id']), '">', options['fn'](this), '</a>'))
Ejemplo n.º 26
0
def _quoted(this, value):
    if value:
        return strlist(
            ['"', value.replace('\\', '\\\\').replace('"', '\\"'), '"'])
Ejemplo n.º 27
0
 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])}))
Ejemplo n.º 28
0
 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))
Ejemplo n.º 29
0
 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])}))