def date_field(name, value=None, data_options=None, **kwargs): id = gen_id() format = get_date_format() # this hack is need for datebox correct working format = format.replace('yy', 'yyyy') _data_options = """ editable:false, formatter:function(date){return dt_formatter(date, %s);}, parser:function(s){return dt_parser(s, %s);} """ % ( json.dumps(format), json.dumps(format) ) if data_options: _data_options += ",%s" % data_options if value: value = format_date(value, format) html = tags.text( name, value, class_="easyui-datebox text w10", id=id, data_options=_data_options, **kwargs ) return html + HTML.literal(""" <script type="text/javascript"> add_datebox_clear_btn("#%s"); </script> """) % id
def market_breadcrumbs(market, cat): market_b = '<li style="display: inline;"><a href="/market/'+market['transformedTitle']+'/">'+market['title']+'</a></li>' cat_b = '' if cat: if cat.has_key('Name'): cat_b = '<li styel="display: inline;"><a href="/market/'+market['transformedTitle']+cat['URL']+'/">'+cat['Name']+'</a></li>' breadcrumbs = market_b+cat_b c.breadcrumbs = HTML.literal(breadcrumbs) return render('/view/blocks/breadcrumbs.mako.html')
def link_to_objects(text): """ Scan a string for "blah blah Content #42 blah blah" and replace "Content #42" with a link to the object editor """ output = HTML.literal() prev_word = None for word in text.split(): if prev_word: id_match = re.match("#(\d+)", word) if id_match: output = output + HTML.a( prev_word+" #"+id_match.group(1), href="/admin/"+prev_word+"/models/"+id_match.group(1)+"/edit") word = None else: output = output + HTML.literal(prev_word) output = output + HTML.literal(" ") prev_word = word if prev_word: output = output + HTML.literal(prev_word) return output
def search_cats(query, ids): """Категории найденных товаров""" if (query and ids) is None: return "" categories_model = CategoriesModel cats = categories_model.get_by_ids(ids) c.cats = '' for cat in cats: if cat['ID'] != 0: c.cats += '<li class="show_tip"><a class="clickable" href="/search' + cat['URL'] +query+ '">' + cat['Name']+'</a><div class="proposal"><a href="' + cat['URL'] + '/"><div class="dotted-text">' +u'на рынок'+ '</div></a></div></li>' c.cats = HTML.literal(c.cats) return render('/view/blocks/market/cats.mako.html')
def view(self, static_page_slug): static_pages_model = StaticPagesModel page = static_pages_model.get_by_slug(static_page_slug) if page is None: abort(status_code=404) c.page_id = page['id'] c.title = page['title'] c.content = HTML.literal(page['content']) c.model = static_pages_model return render('/static.mako.html')
def checkbox(label, name, checked=False, **kwargs): kwargs['type'] = 'checkbox' kwargs['name'] = name if checked: kwargs['checked'] = 'checked' kwargs.setdefault('id', name) return HTML.div(class_='formField checkbox', id='%s-field' % kwargs['id'], c=[HTML.label(for_=name, c=[ HTML.input(**kwargs), HTML.span(class_='labelText', c=[label]) ]), HTML.literal('<form:error name="%s" />' % name)])
def obfuscate_email(email_address): '''Obfuscate an email address for web display (hex encode and delete last 6 chars). Borrowed and simplified from webhelpers.html.tools.mail_to ''' if not email_address: return '' # replace last 5 characters email_address_obfuscated = email_address[:-6] + '....' email_address_obfuscated = HTML.literal(''.join( ['&#%d;' % ord(x) for x in email_address_obfuscated])) return email_address_obfuscated
def _pagerlink(self, pagenr, text): """ Create a URL that links to another page using url_for(). Parameters: pagenr Number of the page that the link points to text Text to be printed in the A-HREF tag """ # Let the url_for() from webhelpers create a new link and set # the variable called 'page_param'. Example: # You are in '/foo/bar' (controller='foo', action='bar') # and you want to add a parameter 'pagenr'. Then you # call the navigator method with page_param='pagenr' and # the url_for() call will create a link '/foo/bar?pagenr=...' # with the respective page number added. link_params = {} # Use the instance kwargs from Page.__init__ as URL parameters link_params.update(self.kwargs) # Add keyword arguments from pager() to the link as parameters link_params.update(self.pager_kwargs) link_params[self.page_param] = pagenr # Create the URL to load the page area part of a certain page (AJAX updates) partial_url = link_params.pop('partial', '') #url_for(**link_params) # Create the URL to load a certain page link_url = link_params.pop('link', request.path_info) link_url = HTML.literal(url(link_url, params=link_params)) if self.onclick: # create link with onclick action for AJAX try: # if '%s' is used in the 'onclick' parameter (backwards compatibility) onclick_action = self.onclick % (partial_url, ) except TypeError: onclick_action = Template(self.onclick).safe_substitute({ "partial_url": partial_url, "page": pagenr }) return HTML.a(text, href=link_url, onclick=onclick_action, **self.link_attr) else: # return static link return HTML.a(text, href=link_url, **self.link_attr)
def paging_toolbar(current_page, total_pages): current_page = int(current_page) total_pages = int(total_pages) if total_pages == 1: return '' pager = '' if current_page <= 5 and total_pages >= 10: for x in range(1, 11): if current_page == x: pager += '<li>'+str(x)+'</li>' else: pager += '<li><a href="'+str(x)+'?'+request.query_string+'">'+str(x)+'</a></li>' elif current_page > (total_pages - 5) and total_pages >= 10: for x in range(total_pages - 8, total_pages+1): if current_page == x: pager += '<li>'+str(x)+'</li>' else: pager += '<li><a href="'+str(x)+'?'+request.query_string+'">'+str(x)+'</a></li>' elif current_page < 10 and total_pages < 10: for x in range(1, total_pages+1): if current_page == x: pager += '<li>'+str(x)+'</li>' else: pager += '<li><a href="'+str(x)+'?'+request.query_string+'">'+str(x)+'</a></li>' elif current_page > 5 and total_pages > 10: for x in range(current_page - 4, current_page + 5): if current_page == x: pager += '<li>'+str(x)+'</li>' else: pager += '<li><a href="'+str(x)+'?'+request.query_string+'">'+str(x)+'</a></li>' if current_page > 1: pager = '<div id="pager-center" align="center"><ul class="pager"><li class="to-start"><a href="1?'+request.query_string+'">to-start</a></li><li class="back"><a href="'+str(current_page-1)+'?'+request.query_string+'">back</a></li>'+pager else: pager = '<div id="pager-center" align="center"><ul class="pager">'+pager if current_page < total_pages: pager += '<li class="next"><a href="'+str(current_page + 1)+'?'+request.query_string+'">next</a></li><li class="to-end"><a href="'+str(total_pages)+'?'+request.query_string+'">to-end</a></li></ul></div>' else: pager += '</ul></div>' return HTML.literal(pager)
def search_breadcrumbs(query, cat): """ возврацает хлебные крошки для страницы производителя Входные параметры: vendor = {} (dict) - текущий производитель cat = {} (dict) - текущая категория Параметры шаблонизатора: c.breadcrumbs = * (string) - сформированные хлебные крошки """ breadcrumbs = '<li style="display: inline;"><a href="/search/' + query + u'">Результаты поиска</a></li>' if cat: if cat.has_key('Name'): breadcrumbs += '<li style="display: inline;"><a href="/search/' + cat['URL']+query+'">' + cat['Name'] + '</a></li>' c.breadcrumbs = HTML.literal(breadcrumbs) return render('/view/blocks/breadcrumbs.mako.html')
def vendor_breadcrumbs(vendor, cat): """ возврацает хлебные крошки для страницы производителя Входные параметры: vendor = {} (dict) - текущий производитель cat = {} (dict) - текущая категория Параметры шаблонизатора: c.breadcrumbs = * (string) - сформированные хлебные крошки """ vendor_b = '<li style="display: inline;"><a href="/vendor/'+vendor['transformedTitle']+'/">'+vendor['name']+'</a></li>' cat_b = '' if cat: if cat.has_key('Name'): cat_b = '<li styel="display: inline;"><a href="/vendor/'+vendor['transformedTitle']+cat['URL']+'/">'+cat['Name']+'</a></li>' breadcrumbs = vendor_b+cat_b c.breadcrumbs = HTML.literal(breadcrumbs) return render('/view/blocks/breadcrumbs.mako.html')
def select_radio(name, title, options, selected=[], help_text=None, **kwargs): expl = None if help_text is not None: expl = HTML.span(class_='helpText', c=help_text) radios = [] for value, label in options: checked = value in selected radios.append(radio(name, value, checked, label, **kwargs)) return HTML.div(class_='formField', id='%s-field' % name, c=[HTML.label(for_=name, c=[ HTML.span(class_='labelText', c=[title]), HTML.span(class_='radioField', c=radios)]), HTML.literal('<form:error name="%s" />' % name), expl])
def input_area(name, title, value='', cols='50', rows='5', help_text=None, disabled=False, **kwargs): expl = None if help_text is not None: expl = HTML.span(class_='helpText', c=help_text) if disabled: kwargs['disabled'] = 'disabled' kwargs.setdefault('id', name) return HTML.div(class_='formField', id='%s-field' % kwargs['id'], c=[HTML.label(for_=name, c=[ HTML.span(class_='labelText', c=[title]), HTML.span(class_='textField', c=[ HTML.textarea(name_=name, cols=cols, rows=rows, c=[value], **kwargs), ])]), HTML.literal('<form:error name="%s" />' % name), expl])
def _pagerlink(self, pagenr, text): """ Create a URL that links to another page using url_for(). Parameters: pagenr Number of the page that the link points to text Text to be printed in the A-HREF tag """ # Let the url_for() from webhelpers create a new link and set # the variable called 'page_param'. Example: # You are in '/foo/bar' (controller='foo', action='bar') # and you want to add a parameter 'pagenr'. Then you # call the navigator method with page_param='pagenr' and # the url_for() call will create a link '/foo/bar?pagenr=...' # with the respective page number added. link_params = {} # Use the instance kwargs from Page.__init__ as URL parameters link_params.update(self.kwargs) # Add keyword arguments from pager() to the link as parameters link_params.update(self.pager_kwargs) link_params[self.page_param] = pagenr # Create the URL to load the page area part of a certain page (AJAX updates) partial_url = link_params.pop('partial', '') #url_for(**link_params) # Create the URL to load a certain page link_url = link_params.pop('link', request.path_info) link_url = HTML.literal(url(link_url, params=link_params)) if self.onclick: # create link with onclick action for AJAX try: # if '%s' is used in the 'onclick' parameter (backwards compatibility) onclick_action = self.onclick % (partial_url,) except TypeError: onclick_action = Template(self.onclick).safe_substitute({ "partial_url": partial_url, "page": pagenr }) return HTML.a(text, href=link_url, onclick=onclick_action, **self.link_attr) else: # return static link return HTML.a(text, href=link_url, **self.link_attr)
def vendor_cats(vendor): if len(vendor): reference_model = ReferenceModel categories_model = CategoriesModel tempo = reference_model.group(keys={'categoryId':True}, condition={'vendor': vendor['id']}) cats = [] for item in tempo: cats.append(item['categoryId']) cats = categories_model.get_by_ids(cats) c.cats = '' for cat in cats: if cat['ID'] != 0: c.cats += '<li class="show_tip"><a class="clickable" href="/vendor/' + vendor['transformedTitle'] + cat['URL'] + '/">' + cat['Name']+'</a><div class="proposal"><a href="' + cat['URL'] + '/"><div class="dotted-text">' +u'на рынок'+ '</div></a></div></li>' c.cats = HTML.literal(c.cats) return render('/view/blocks/vendor/cats.mako.html') else: return ""
def market_cats(market): if len(market)>0: reference_model = ReferenceModel categories_model = CategoriesModel tempo = reference_model.group(keys={'categoryId':True}, condition={'shopId': market['id']}) cats = [] for item in tempo: cats.append(item['categoryId']) cats = categories_model.get_by_ids(cats) c.cats = '' for cat in cats: if cat['ID'] != 0: c.cats += '<li class="show_tip"><a class="clickable" href="/market/' + market['transformedTitle'] + cat['URL'] + '/">' + cat['Name']+'</a><div class="proposal"><a href="' + cat['URL'] + u'/"><div title="Показать все товары этой категории на рынке" class="dotted-text">' +u'на рынок'+ '</div></a></div></li>' c.cats = HTML.literal(c.cats) return render('/view/blocks/market/cats.mako.html') else: return ""
def cat_breadcrumbs(current_cat={}): breadcrumbs = '' if current_cat: url = current_cat['URL'] url = url[1:len(url)] categories = CategoriesModel splited = url.split('/') url = '' for item in splited: if item is '': continue url += '/' + item category = categories.getByURL(url) if category: breadcrumbs += '<li style="display: inline;"><a href="' + url + '/">'+ unicode(category["Name"]) + '</a></li>' else: breadcrumbs = u'<li style="display: inline;"><span>Главная</span></li>' c.breadcrumbs = HTML.literal(breadcrumbs) return render('/view/blocks/breadcrumbs.mako.html')
def select_line(name, title, options, selected=[], help_text=None, right_next=None, **kwargs): expl = None if help_text is not None: expl = HTML.span(class_='helpText', c=help_text) next = None if right_next is not None: next = HTML.span(class_='rightNext', c=right_next) kwargs.setdefault('id', name) field = select(name, selected, options, **kwargs) return HTML.div(class_='formField', id='%s-field' % kwargs['id'], c=[HTML.label(for_=name, c=[ HTML.span(class_='labelText', c=[title]), HTML.span(class_='textField', c=[ field, ])]), next, HTML.literal('<form:error name="%s" />' % name), expl])
def input_line(name, title, value='', help_text=None, right_next=None, **kwargs): expl = None if help_text is not None: expl = HTML.span(class_='helpText', c=help_text) next = None if right_next is not None: next = HTML.span(class_='rightNext', c=right_next) kwargs.setdefault('id', name) kwargs.setdefault('type', 'text') return HTML.div(class_='formField', id='%s-field' % kwargs['id'], c=[HTML.label(for_=name, c=[ HTML.span(class_='labelText', c=[title]), HTML.span(class_='textField', c=[ HTML.input(value=value, name_=name, **kwargs), ])]), next, HTML.literal('<form:error name="%s" />' % name), expl])
def datetime_field(name, value=None, data_options=None, **kwargs): id = gen_id() _data_options = """ editable:false, showSeconds:false, formatter:function(date){return dt_formatter(date, %s);}, parser:function(s){return dt_parser(s, %s);} """ % ( json.dumps(get_datetime_format()), json.dumps(get_datetime_format()) ) if data_options: _data_options += ",%s" % data_options if value: value = format_datetime(value) html = tags.text( name, value, class_="easyui-datetimebox text w10", id=id, data_options=_data_options, **kwargs ) return html + HTML.literal(""" <script type="text/javascript"> add_datetimebox_clear_btn("#%s"); </script> """) % id
def mail_to(email_address, name=None, cc=None, bcc=None, subject=None, body=None, replace_at=None, replace_dot=None, encode=None, **html_options): """Create a link tag for starting an email to the specified ``email_address``. This ``email_address`` is also used as the name of the link unless ``name`` is specified. Additional HTML options, such as class or id, can be passed in the ``html_options`` hash. You can also make it difficult for spiders to harvest email address by obfuscating them. Examples:: >>> mail_to("*****@*****.**", "My email", encode = "javascript") literal(u'<script type="text/javascript">\\n//<![CDATA[\\neval(unescape(\\'%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%4d%79%20%65%6d%61%69%6c%3c%2f%61%3e%27%29%3b\\'))\\n//]]>\\n</script>') >>> mail_to("*****@*****.**", "My email", encode = "hex") literal(u'<a href="mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>') You can also specify the cc address, bcc address, subject, and body parts of the message header to create a complex e-mail using the corresponding ``cc``, ``bcc``, ``subject``, and ``body`` keyword arguments. Each of these options are URI escaped and then appended to the ``email_address`` before being output. **Be aware that javascript keywords will not be escaped and may break this feature when encoding with javascript.** Examples:: >>> mail_to("*****@*****.**", "My email", cc="*****@*****.**", bcc="*****@*****.**", subject="This is an example email", body= "This is the body of the message.") literal(u'<a href="mailto:[email protected]?cc=ccaddress%40domain.com&bcc=bccaddress%40domain.com&subject=This%20is%20an%20example%20email&body=This%20is%20the%20body%20of%20the%20message.">My email</a>') """ extras = [] for item in ('cc', cc), ('bcc', bcc), ('subject', subject), ('body', body): option = item[1] if option: if not isinstance(option, literal): item = (item[0], escape(option)) extras.append(item) options_query = urllib.urlencode(extras).replace("+", "%20") protocol = 'mailto:' email_address_obfuscated = email_address if replace_at: email_address_obfuscated = email_address_obfuscated.replace('@', replace_at) if replace_dot: email_address_obfuscated = email_address_obfuscated.replace('.', replace_dot) if encode == 'hex': email_address_obfuscated = HTML.literal(''.join( ['&#%d;' % ord(x) for x in email_address_obfuscated])) protocol = HTML.literal(''.join(['&#%d;' % ord(x) for x in protocol])) word_re = re.compile('\w') encoded_parts = [] for x in email_address: if word_re.match(x): encoded_parts.append('%%%x' % ord(x)) else: encoded_parts.append(x) email_address = HTML.literal(''.join(encoded_parts)) url = HTML.literal(protocol + email_address) if options_query: url += HTML.literal('?') + options_query html_options['href'] = url tag = HTML.a(name or email_address_obfuscated, **html_options) if encode == 'javascript': tmp = "document.write('%s');" % tag string = ''.join(['%%%x' % ord(x) for x in tmp]) return HTML.script( HTML.literal("\n//<![CDATA[\neval(unescape('%s'))\n//]]>\n" % string), type="text/javascript") else: return tag
def mail_to(email_address, name=None, cc=None, bcc=None, subject=None, body=None, replace_at=None, replace_dot=None, encode=None, **html_attrs): """Create a link tag for starting an email to the specified ``email_address``. This ``email_address`` is also used as the name of the link unless ``name`` is specified. Additional HTML options, such as class or id, can be passed in the ``html_attrs`` hash. You can also make it difficult for spiders to harvest email address by obfuscating them. Examples:: >>> mail_to("*****@*****.**", "My email", encode = "javascript") literal(u'<script type="text/javascript">\\n//<![CDATA[\\neval(unescape(\\'%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%4d%79%20%65%6d%61%69%6c%3c%2f%61%3e%27%29%3b\\'))\\n//]]>\\n</script>') >>> mail_to("*****@*****.**", "My email", encode = "hex") literal(u'<a href="mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>') You can also specify the cc address, bcc address, subject, and body parts of the message header to create a complex e-mail using the corresponding ``cc``, ``bcc``, ``subject``, and ``body`` keyword arguments. Each of these options are URI escaped and then appended to the ``email_address`` before being output. **Be aware that javascript keywords will not be escaped and may break this feature when encoding with javascript.** Examples:: >>> mail_to("*****@*****.**", "My email", cc="*****@*****.**", bcc="*****@*****.**", subject="This is an example email", body= "This is the body of the message.") literal(u'<a href="mailto:[email protected]?cc=ccaddress%40domain.com&bcc=bccaddress%40domain.com&subject=This%20is%20an%20example%20email&body=This%20is%20the%20body%20of%20the%20message.">My email</a>') """ extras = [] for item in ('cc', cc), ('bcc', bcc), ('subject', subject), ('body', body): option = item[1] if option: if not isinstance(option, literal): item = (item[0], escape(option)) extras.append(item) options_query = urllib.urlencode(extras).replace("+", "%20") protocol = 'mailto:' email_address_obfuscated = email_address if replace_at: email_address_obfuscated = email_address_obfuscated.replace('@', replace_at) if replace_dot: email_address_obfuscated = email_address_obfuscated.replace('.', replace_dot) if encode == 'hex': email_address_obfuscated = HTML.literal(''.join( ['&#%d;' % ord(x) for x in email_address_obfuscated])) protocol = HTML.literal(''.join(['&#%d;' % ord(x) for x in protocol])) word_re = re.compile('\w') encoded_parts = [] for x in email_address: if word_re.match(x): encoded_parts.append('%%%x' % ord(x)) else: encoded_parts.append(x) email_address = HTML.literal(''.join(encoded_parts)) url = HTML.literal(protocol + email_address) if options_query: url += HTML.literal('?') + options_query html_attrs['href'] = url tag = HTML.a(name or email_address_obfuscated, **html_attrs) if encode == 'javascript': tmp = "document.write('%s');" % tag string = ''.join(['%%%x' % ord(x) for x in tmp]) return HTML.script( HTML.literal("\n//<![CDATA[\neval(unescape('%s'))\n//]]>\n" % string), type="text/javascript") else: return tag
def input_hidden(name, value='', **kwargs): kwargs.setdefault('id', name) return HTML.div(class_='formField', id='%s-field' % kwargs['id'], c=[HTML.input(type='hidden', value=value, name_=name, **kwargs), HTML.literal('<form:error name="%s" />' % name)])
def input_wysiwyg(name, title, value='', cols='60', rows='15'): return HTML.div(class_='form-field', c=[ HTML.label(for_=name, c=[title]), HTML.textarea(class_='ckeditor', name_=name, id_=name, cols=cols, rows=rows, c=[value]), HTML.literal('<form:error name="%s" />' % name) ])
title = market['title'].lower() url = ''.join(["/market/", market['transformedTitle'], "/"]) id = '' if market['title'][0] != first_letter: first_letter = market['title'][0] if first_letter in digits: id = ' id="SHOP_DIGITS"' else: id = ''.join([' id="SHOP_', first_letter, '"']) c.markets.extend(['<li', id, '><a href="', url, '">', title, '</a></li>']) except KeyError, e: print '%s key in markets does not exists, viewhelpers.py in vendors() ' % e c.markets = ''.join(c.markets) c.vendors = HTML.literal(c.vendors) c.markets = HTML.literal(c.markets) return render('/view/blocks/vendors.mako.html') def vendors_list(): c.vendors = [] vendors = VendorsModel.get_all()#h.get_vendors() for vendor in vendors: try: url = ''.join(['/vendor/', vendor['transformedTitle'], '/']) id = '' c.vendors.extend(['<li', id, '><a href="', url, '">', vendor['name'], '</a></li>']) except KeyError, e: print '%s key in vendors does not exists, viewhelpers.py in vendors() ' % e c.vendors = ''.join(c.vendors)
def test_mail_to_with_img(self): self.assertEqual( u'<a href="mailto:[email protected]"><img src="/feedback.png" /></a>', mail_to("*****@*****.**", HTML.literal('<img src="/feedback.png" />')), )
def test_mail_to_with_img(self): self.assertEqual( '<a href="mailto:[email protected]"><img src="/feedback.png" /></a>', mail_to('*****@*****.**', HTML.literal('<img src="/feedback.png" />')))
def test_link_tag_with_query_and_no_name(self): eq_( "<a href=\"http://www.example.com?q1=v1&q2=v2\">http://www.example.com?q1=v1&q2=v2</a>", link_to(None, HTML.literal("http://www.example.com?q1=v1&q2=v2")))
def test_link_tag_with_query_and_no_name(self): eq_( u"<a href=\"http://www.example.com?q1=v1&q2=v2\">http://www.example.com?q1=v1&q2=v2</a>", link_to(None, HTML.literal("http://www.example.com?q1=v1&q2=v2")))