def pager( self, format='<ul class="pagination">$link_previous ~2~ $link_next</ul>', page_param='page', partial_param='partial', show_if_single_page=False, separator=' ', onclick=None, symbol_first='<<', symbol_last='>>', symbol_previous='<', symbol_next='>', link_attr=None, curpage_attr=None, dotdot_attr=None, **kwargs): self.curpage_attr = curpage_attr or {'class': 'active'} self.separator = separator self.pager_kwargs = kwargs self.page_param = page_param self.partial_param = partial_param self.onclick = onclick self.link_attr = link_attr or { 'class': 'pager_link', 'rel': 'prerender' } self.dotdot_attr = dotdot_attr or {'class': 'pager_dotdot'} # Don't show navigator if there is no more than one page if self.page_count == 0 or (self.page_count == 1 and not show_if_single_page): return '' from string import Template # Replace ~...~ in token format by range of pages result = re.sub(r'~(\d+)~', self._range, format) # Interpolate '%' variables result = Template(result).safe_substitute({ 'first_page': self.first_page, 'last_page': self.last_page, 'page': self.page, 'page_count': self.page_count, 'items_per_page': self.items_per_page, 'first_item': self.first_item, 'last_item': self.last_item, 'item_count': self.item_count, 'link_first': self.page > self.first_page and \ self._pagerlink(self.first_page, symbol_first) or '', 'link_last': self.page < self.last_page and \ self._pagerlink(self.last_page, symbol_last) or '', 'link_previous': HTML.li(self.previous_page and \ self._pagerlink(self.previous_page, symbol_previous) \ or HTML.a(symbol_previous)), 'link_next': HTML.li(self.next_page and \ self._pagerlink(self.next_page, symbol_next) \ or HTML.a(symbol_next)) }) return literal(result)
def threads(self): import sys import traceback items = sys._current_frames().items() dumps = [] for thread, frame in items: dumps.append({ "id": str(thread), "info": _get_info(frame), "trace": "\n".join(traceback.format_stack(frame)), }) from webhelpers.html import HTML, literal out = literal() out += str(len(items)) + " threads:\n" for data in dumps: out += HTML.br() out += HTML.a(data["info"], href="#" + data["id"]) for data in dumps: out += HTML.hr() out += HTML.a(data["id"] + ": " + HTML.b(data["info"]), name=data["id"]) out += HTML.p() out += HTML.pre(data["trace"]) return out
def _pagerlink(self, page, text): # 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 'page'. Then you # call the navigator method with page_param='page' and # the url_for() call will create a link '/foo/bar?page=...' # 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] = page # Get the URL generator if self._url_generator is not None: url_generator = self._url_generator else: try: import pylons url_generator = pylons.url.current except (ImportError, AttributeError): try: import routes url_generator = routes.url_for config = routes.request_config() except (ImportError, AttributeError): raise NotImplementedError("no URL generator available") else: # if the Mapper is configured with explicit=True we have to fetch # the controller and action manually if config.mapper.explicit: if hasattr(config, 'mapper_dict'): for k, v in config.mapper_dict.items(): if k != self.page_param: link_params[k] = v # Create the URL to load a certain page link_url = url_generator(**link_params) if self.onclick: # create link with onclick action for AJAX # Create the URL to load the page area part of a certain page (AJAX # updates) link_params[self.partial_param] = 1 partial_url = url_generator(**link_params) 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": page }) a_tag = HTML.a(text, href=link_url, onclick=onclick_action, **self.link_attr) else: # return static link a_tag = HTML.a(text, href=link_url, **self.link_attr) li_tag = HTML.li(a_tag) return li_tag
def display_user_list(self, users, user): page = context.page request = context.request page.title = "User List" page.heading = "User List" page.add_block(NavBlock(force_pager=True)) headers = [] tds = [ HTML.th("ID", width="16"), HTML.th("Av.", width="16", title="Avatar"), HTML.th("Username"), HTML.th("Join Date"), HTML.th("Ps.", width="16", title="Post Count"), HTML.th("Cs.", width="16", title="Comment Count"), ] if user.can("view_user_email"): tds.append(HTML.th("Email Address")) tds.append(HTML.th("Action")) headers.append(HTML.tr(*tds)) tds = [ "", # HTML.input(name="page", type="hidden", value=request.args.get("page", "1")), tags.checkbox("avatar", checked=request.args.get("avatar")), tags.text("username", value=request.args.get("username")), "", tags.checkbox("posts", value="1", checked=request.args.get("posts")), tags.checkbox("comments", value="1", checked=request.args.get("comments")), ] if user.can("view_user_email"): tds.append(tags.text("email", value=request.args.get("email"))) tds.append(tags.submit(name="submit", value="Search")) headers.append(HTML.tr(HTML.form(*[HTML.td(x) for x in tds], action="#", method="GET"))) rows = [] for duser in users: assert isinstance(duser, User) tds = [ duser.id, duser.get_avatar_html(16), HTML.a(duser.username, href=make_link("user/"+duser.username)), str(duser.join_date)[:16], HTML.a(duser.post_count, href=make_link("post/list/uploaded_by_id=%d/1" % duser.id)), duser.comment_count, ] if user.can("view_user_email"): tds.append(duser.email) tds.append("") rows.append(HTML.tr(*[HTML.td(x) for x in tds])) page.add_block(Block( "Users", HTML.table(HTML.thead(*headers), HTML.tbody(*rows), class_="zebra") ))
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 a certain page link_url = link_params.get('link', request.path_info) link_url = '%s?page=%s' % (link_url, pagenr) # Create the URL to load the page area part of a certain page (AJAX updates) #link_params[self.partial_param] = 1 partial_url = link_params.get('partial', '') #url_for(**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 _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 a certain page link_url = link_params.get('link', request.path_info) if '?' in link_url: link_url = '%s&page=%s'%(link_url, pagenr) else: link_url = '%s?page=%s'%(link_url, pagenr) # Create the URL to load the page area part of a certain page (AJAX updates) #link_params[self.partial_param] = 1 partial_url = link_params.get('partial', '') #url_for(**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 __init__(self, force_pager=False): from shimpy.core.context import context request = context.request page_num = int(request.args.get("page", 1)) nav = [] if force_pager or "page" in request.args: nav.append(HTML.a("Prev", href=update_params(request.full_path, page=page_num-1))) nav.append(HTML.a("Index", href="/")) if force_pager or "page" in request.args: nav.append(HTML.a("Next", href=update_params(request.full_path, page=page_num+1))) Block.__init__(self, "Navigation", HTML.span(literal(" | ").join(nav)), "left", 0)
def pager(self, format='<ul class="pagination">$link_previous ~2~ $link_next</ul>', page_param='page', partial_param='partial', show_if_single_page=False, separator=' ', onclick=None, symbol_first='<<', symbol_last='>>', symbol_previous='<', symbol_next='>', link_attr=None, curpage_attr=None, dotdot_attr=None, **kwargs): self.curpage_attr = curpage_attr or {'class': 'active'} self.separator = separator self.pager_kwargs = kwargs self.page_param = page_param self.partial_param = partial_param self.onclick = onclick self.link_attr = link_attr or {'class': 'pager_link', 'rel': 'prerender'} self.dotdot_attr = dotdot_attr or {'class': 'pager_dotdot'} # Don't show navigator if there is no more than one page if self.page_count == 0 or (self.page_count == 1 and not show_if_single_page): return '' from string import Template # Replace ~...~ in token format by range of pages result = re.sub(r'~(\d+)~', self._range, format) # Interpolate '%' variables result = Template(result).safe_substitute({ 'first_page': self.first_page, 'last_page': self.last_page, 'page': self.page, 'page_count': self.page_count, 'items_per_page': self.items_per_page, 'first_item': self.first_item, 'last_item': self.last_item, 'item_count': self.item_count, 'link_first': self.page > self.first_page and \ self._pagerlink(self.first_page, symbol_first) or '', 'link_last': self.page < self.last_page and \ self._pagerlink(self.last_page, symbol_last) or '', 'link_previous': HTML.li(self.previous_page and \ self._pagerlink(self.previous_page, symbol_previous) \ or HTML.a(symbol_previous)), 'link_next': HTML.li(self.next_page and \ self._pagerlink(self.next_page, symbol_next) \ or HTML.a(symbol_next)) }) return literal(result)
def dataset_link_from_activity(activity): href = dataset_href_from_activity(activity) if not href: return '' try: title = activity['data']['package']['title'] return HTML.a(title, href=href) except KeyError: return ''
def test_html(): a = HTML.a(href='http://mostlysafe" <tag', c="Bad <script> tag") assert u'<a href="http://mostlysafe" <tag">Bad <script> tag</a>' == a img = HTML.img(src="http://some/image.jpg") assert u'<img src="http://some/image.jpg" />' == img br = HTML.br() assert u"<br />" == br
def test_html(): a = HTML.a(href='http://mostlysafe\" <tag', c="Bad <script> tag") eq_(a, '<a href="http://mostlysafe" <tag">Bad <script> tag</a>') img = HTML.img(src='http://some/image.jpg') eq_(img, '<img src="http://some/image.jpg" />') br = HTML.br() eq_('<br />', br)
def test_html(): a = HTML.a(href='http://mostlysafe\" <tag', c="Bad <script> tag") eq_(a, u'<a href="http://mostlysafe" <tag">Bad <script> tag</a>') img = HTML.img(src='http://some/image.jpg') eq_(img, u'<img src="http://some/image.jpg" />') br = HTML.br() eq_(u'<br />', br)
def th_sortable(current_order, column_order, label, url, class_if_sort_column="sort", class_if_not_sort_column=None, link_attrs=None, name="th", **attrs): """<th> for a "click-to-sort-by" column. Convenience function for a sortable column. If this is the current sort column, just display the label and set the cell's class to ``class_if_sort_column``. ``current_order`` is the table's current sort order. ``column_order`` is the value pertaining to this column. In other words, if the two are equal, the table is currently sorted by this column. If this is the sort column, display the label and set the <th>'s class to ``class_if_sort_column``. If this is not the sort column, display an <a> hyperlink based on ``label``, ``url``, and ``link_attrs`` (a dict), and set the <th>'s class to ``class_if_not_sort_column``. ``url`` is the literal href= value for the link. Pylons users would typically pass something like ``url=h.url_for("mypage", sort="date")``. ``**attrs`` are additional attributes for the <th> tag. If you prefer a <td> tag instead of <th>, pass ``name="td"``. To change the sort order via client-side Javascript, pass ``url=None`` and the appropriate Javascript attributes in ``link_attrs``. Examples: >>> sort = "name" >>> th_sortable(sort, "name", "Name", "?sort=name") literal(u'<th class="sort">Name</th>') >>> th_sortable(sort, "date", "Date", "?sort=date") literal(u'<th><a href="?sort=date">Date</a></th>') >>> th_sortable(sort, "date", "Date", None, link_attrs={"onclick": "myfunc()"}) literal(u'<th><a onclick="myfunc()">Date</a></th>') """ from webhelpers.html import HTML if current_order == column_order: content = label class_ = class_if_sort_column else: link_attrs = link_attrs or {} content = HTML.a(label, href=url, **link_attrs) class_ = class_if_not_sort_column return HTML.th(content, class_=class_, **attrs)
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_options) a_options['href'] = literal(prefix + link) return literal(before) + HTML.a(text, **a_options) + literal(after)
def _range(self, regexp_match): html = super(Page, self)._range(regexp_match) # Convert .. dotdot = "\.\." dotdot_link = HTML.li(HTML.a("...", href="#"), class_="disabled") html = re.sub(dotdot, dotdot_link, html) # Convert current page text = "%s" % self.page current_page_span = str(HTML.span(c=text, **self.curpage_attr)) current_page_link = self._pagerlink(self.page, text, extra_attributes=self.curpage_attr) return re.sub(current_page_span, current_page_link, html)
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 _pagerlink(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 """ from routes import url_for # 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(kwargs) link_params[page_param] = pagenr # Create the URL to load a certain page link_url = url_for(**link_params) # Create the URL to load the page area part of a certain page (AJAX updates) link_params[partial_param] = 1 partial_url = url_for(**link_params) if onclick: # create link with onclick action for AJAX onclick_action = onclick % (partial_url, ) return HTML.a(text, href=link_url, onclick=onclick_action, **link_attr) else: # return static link return HTML.a(text, href=link_url, **link_attr)
def h1(title, id=None, tag='h1', **attrs): """Returns an <h1> tag that links to itself. `title` is the text inside the tag. `id` is the HTML id to use; if none is provided, `title` will be munged into something appropriate. """ if not id: id = sanitize_id(title) link = HTML.a(title, href='#' + id, class_='subtle') return HTML.tag(tag, link, id=id, **attrs)
def _range(self, regexp_match): html = super(Page, self)._range(regexp_match) # Convert .. dotdot = '<span class="pager_dotdot">..</span>' dotdot_link = HTML.li(HTML.a('...', href='#'), class_='disabled') html = re.sub(dotdot, dotdot_link, html) # Convert current page text = '%s' % self.page current_page_span = str(HTML.span(c=text, **self.curpage_attr)) current_page_link = self._pagerlink(self.page, text, extra_attributes=self.curpage_attr) return re.sub(current_page_span, current_page_link, html)
def link_to(label, url='', **attrs): """Create a hyperlink with the given text pointing to the URL. If the label is ``None`` or empty, the URL will be used as the label. This function does not modify the URL in any way. The label will be escaped if it contains HTML markup. To prevent escaping, wrap the label in a ``webhelpers.html.literal()``. """ attrs['href'] = url if label == '' or label is None: label = url return HTML.a(label, **attrs)
def frag_link(value, title='', class_='', href_tuple=([], {}), data=None): #*args, **kwargs href, href_frag = url_pair(gen_format='frag', *href_tuple[0], **href_tuple[1]) # generate standard and frag URL's kwargs = {'data-frag' : href_frag} if data: kwargs.update(dict([('data-'+k, v) for k,v in data.iteritems()])) return HTML.a( value , href = href , class_ = class_ + ' link_new_frag' , title = title if title else value, ##onClick ="cb_frag($(this), '%s'); return false;" % href_frag , **kwargs )
def test_newline_arg(): eq_(HTML.a(), literal(u'<a></a>')) eq_(HTML.a(_nl=True), literal(u'<a>\n</a>\n')) eq_(HTML.a(_closed=False), literal(u'<a>')) eq_(HTML.a(_closed=False, _nl=True), literal(u'<a>\n')) eq_(HTML.a("A", "B", href="/"), literal(u'<a href="/">AB</a>')) eq_(HTML.a("A", "B", href="/", _nl=True), literal(u'<a href="/">\nA\nB\n</a>\n'))
def test_newline_arg(): eq_(HTML.a(), literal(u'<a></a>')) eq_(HTML.a(_nl=True), literal(u'<a>\n</a>\n')) eq_(HTML.a(_closed=False), literal(u'<a>')) eq_(HTML.a(_closed=False, _nl=True), literal(u'<a>\n')) eq_(HTML.a("A", "B", href="/"), literal(u'<a href="/">AB</a>')) eq_(HTML.a( "A", "B", href="/", _nl=True), literal(u'<a href="/">\nA\nB\n</a>\n'))
def _pagerlink(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 """ from routes import url_for # 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(kwargs) link_params[page_param] = pagenr # Create the URL to load a certain page link_url = url_for(**link_params) # Create the URL to load the page area part of a certain page (AJAX updates) link_params[partial_param] = 1 partial_url = url_for(**link_params) if onclick: # create link with onclick action for AJAX onclick_action = onclick % (partial_url,) return HTML.a(text, href=link_url, onclick=onclick_action, **link_attr) else: # return static link return HTML.a(text, href=link_url, **link_attr)
def th_sortable(current_order, column_order, label, url, class_if_sort_column="sort", class_if_not_sort_column=None, link_attrs=None, name="th", **attrs): """<th> for a "click-to-sort-by" column. Convenience function for a sortable column. If this is the current sort column, just display the label and set the cell's class to ``class_if_sort_column``. ``current_order`` is the table's current sort order. ``column_order`` is the value pertaining to this column. In other words, if the two are equal, the table is currently sorted by this column. If this is the sort column, display the label and set the <th>'s class to ``class_if_sort_column``. If this is not the sort column, display an <a> hyperlink based on ``label``, ``url``, and ``link_attrs`` (a dict), and set the <th>'s class to ``class_if_not_sort_column``. ``url`` is the literal href= value for the link. Pylons users would typically pass something like ``url=h.url_for("mypage", sort="date")``. ``**attrs`` are additional attributes for the <th> tag. If you prefer a <td> tag instead of <th>, pass ``name="td"``. To change the sort order via client-side Javascript, pass ``url=None`` and the appropriate Javascript attributes in ``link_attrs``. Examples: >>> sort = "name" >>> th_sortable(sort, "name", "Name", "?sort=name") literal(%(u)s'<th class="sort">Name</th>') >>> th_sortable(sort, "date", "Date", "?sort=date") literal(%(u)s'<th><a href="?sort=date">Date</a></th>') >>> th_sortable(sort, "date", "Date", None, link_attrs={"onclick": "myfunc()"}) literal(%(u)s'<th><a onclick="myfunc()">Date</a></th>') """ from webhelpers.html import HTML if current_order == column_order: content = label class_ = class_if_sort_column else: link_attrs = link_attrs or {} content = HTML.a(label, href=url, **link_attrs) class_ = class_if_not_sort_column return HTML.th(content, class_=class_, **attrs)
def handle_match(matchobj): # The pattern contains a space so we only find usernames that # has a whitespace in front, we save the spaced so we can but # it back after the transformation space, userid = matchobj.group(1, 2) #Force lowercase userid userid = userid.lower() if userid in users: user = users[userid] tag = {} tag['href'] = request.resource_url(meeting, '_userinfo', query={'userid': userid}).replace(request.application_url, '') tag['title'] = user.title tag['class'] = "inlineinfo" return space + HTML.a('@%s' % userid, **tag) else: return space + '@' + userid
def display_login_block(self): page = context.page table = HTML.table( HTML.tr( HTML.th("Username"), HTML.td(tags.text("username")), ), HTML.tr( HTML.th("Password"), HTML.td(tags.password("password")), ), HTML.tr( HTML.td(tags.submit(name="submit", value="Log In"), colspan=2) ), HTML.tr( HTML.td(HTML.small(HTML.a("Create Account", href=make_link("user_admin/create"))), colspan=2) ), # class_="form", ) form = HTML.form(table, action=make_link("user_admin/login"), method="POST") page.add_block(Block("Login", form, self._user_block_location(), 90))
def handle_match(matchobj): # The pattern contains a space so we only find usernames that # has a whitespace in front, we save the spaced so we can but # it back after the transformation space, userid = matchobj.group(1, 2) #Force lowercase userid userid = userid.lower() if userid in users: user = users[userid] tag = {} tag['href'] = request.resource_url(meeting, '_userinfo', query={ 'userid': userid }).replace( request.application_url, '') tag['title'] = user.title tag['class'] = "inlineinfo" return space + HTML.a('@%s' % userid, **tag) else: return space + '@' + userid
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 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 _pagerlink(self, page, text): """ Create a URL that links to another page using url_for(). Parameters: page Number of the page that the link points to text Text to be printed in the A-HREF tag """ from routes import url_for, request_config # 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 'page'. Then you # call the navigator method with page_param='page' and # the url_for() call will create a link '/foo/bar?page=...' # 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] = page # Get the URL generator if self._url_generator is not None: url_generator = self._url_generator else: try: import pylons url_generator = pylons.url.current except (ImportError, AttributeError): try: import routes url_generator = routes.url_for config = routes.request_config() except (ImportError, AttributeError): raise NotImplementedError("no URL generator available") else: # if the Mapper is configured with explicit=True we have to fetch # the controller and action manually if config.mapper.explicit: if hasattr(config, 'mapper_dict'): for k, v in config.mapper_dict.items(): link_params[k] = v # Create the URL to load a certain page link_url = url_generator(**link_params) if self.onclick: # create link with onclick action for AJAX # Create the URL to load the page area part of a certain page (AJAX # updates) link_params[self.partial_param] = 1 partial_url = url_generator(**link_params) 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": page }) 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 secure_link(href, value='Submit', value_formatted=None, title=None, method='post', form_data=None, link_data=None, link_class='', parent_id=None, force_profile=False): #def secure_link(href, value='Submit', value_formatted=None, css_class='', title=None, rel=None, confirm_text=None, method='POST', json_form_complete_actions='', modal_params=None, data={}): """ Create two things: - A visible HTML form which POSTs some data along with an auth token - An invisible pretty-looking plain-text link which calls form.submit() Then use javascript to hide the form and show the pretty link @param href - can be supplied as a string or a tuple in the format (args, kwargs), this tuple will then be used to automatically create href_json @param href_json - an optional JSON url to post to can be provided, this will then activate an AJAX call, this is normally set automatically by providing a tuple for href (see above) @param javascript_json_complete_actions - a string of javascript that is activated on a successful AJAX call. Normally used to refresh parts of the page that have been updated from the successful AJAX call. """ if not value_formatted: value_formatted = value else: value_formatted = literal(value_formatted) if not form_data: form_data = {} if not link_data: link_data = {} # Setup Get string href ---- # the href could be passed a a tuple of (args,kwargs) for form() to create a JSON version to submit to # we need a text compatable href reguardless href_original = copy.deepcopy(href) if isinstance(href, tuple): args = href[0] kwargs = href[1] form_href = url(*args, **kwargs) kwargs['format'] = 'json' data_json = url(*args, **kwargs) #form_data = dict([(key.replace('_', '-' if '_' in key else key, form_data[key])) for key in form_data.keys()]) # GregM: Work out what to do is json_complete has not been defined manually, this could and will fail on odd cercumstances if not form_data.get('json_complete'): args = list(args) args[0] = action_single_map.get(args[0], args[0]) if kwargs.get('format'): del kwargs['format'] kwargs['action'] = 'show' action1 = ['remove'] if method == 'DELETE' or method == 'delete' else ['update'] action2 = ['update', [url(*args, **kwargs)], None, None] if parent_id: kwargs['id'] = parent_id action2[1].append(url(*args, **kwargs)) if args[0] == 'member' or force_profile: action2[1].append('/profile') form_data['json_complete'] = json.dumps([action1, action2]).replace('"',"'") # Do magic to convert all form & link _data to kwargs form_data = dict([ ('data-%s' % k.replace('_','-'), v if isinstance(v, basestring) else json.dumps(v)) for (k,v) in form_data.items() ]) link_data = dict([ ('data-%s' % k.replace('_','-'), v if isinstance(v, basestring) else json.dumps(v)) for (k,v) in link_data.items() ]) # Keep track of number of secure links created so they can all have unique hash's #hhash = hashlib.md5(uniqueish_id(href, value, vals)).hexdigest()[0:6] # GregM: Semi-unique ids required for selenium, these will be unique to every action (multiple of same action can exist) # hhash = re.sub(funky_chars, '_', re.sub(link_matcher, '', href)) + '_' + method # Create Form -------- #AllanC: without the name attribute here the AJAX/JSON does not function, WTF! took me ages to track down :( NOTE: if the name="submit" jQuery wont submit! a known problem!? hf = form(href_original, method=method, class_='hide_if_js', **form_data) + \ HTML.input(type="submit", value=value, name=value) + \ end_form() #, hl = HTML.a( value_formatted , href = '#', class_ = link_class + ' hide_if_nojs link_secure', # GregM: secure_show means js will show element and remove class (to stop dup processing of same element) title = title, **link_data ) return HTML.span(hf+hl, class_="secure_link") #+json_submit_script
def gen_link(o): # AllanC - code inspired from Shish's Message link framework in lib/communication/messages.py if hasattr(o, "__link__"): return HTML.a(unicode(o), href=o.__link__()) else: return HTML.span(unicode(o)) # the span here is for security, it does HTML escaping