def _get_label(field, colon=True, required=True): if not field._label: return '' if not (required and field.required): required_html = '' else: required_html = Html('<sup class="required">*</sup>') colon_html = Html('<span class="colon">:</span>') if colon else '' return Html('<label for="%s">%s%s%s</label>') % ( field.attrs['id'], field._label, required_html, colon_html)
def header(form): result = [form.tag] for f in form.hidden_fields: result.append(f.html) for f in form.fields: hidden = f.hidden if hidden: result.append(hidden) return Html('\n') + Html('\n').join(result)
def __unicode__(self): result = [htmltag('div', {'class':'pony-tabs clearfix'}, **self.attrs), Html('\n<ul>\n') ] for name, markup, attrs in self._tabs: result.append(Html('<li><a href="#%s"><span>%s</span></a>\n') % (attrs['id'], name)) result.append(Html('</ul>\n')) for name, markup, attrs in self._tabs: result.extend([htmltag('div', {'class': 'pony-tab clearfix'}, **attrs), markup, Html('</div>\n')]) result.append(Html('</div>')) return Html('').join(result)
def button(link, markup, **attrs): result = [ htmltag('a', { 'class': 'button', 'href': link }, **attrs), Html('<span>%s</span></a>') % markup ] return Html('').join(result)
def rounded(markup, **attrs): tagname = attrs.pop('tagname', 'div') radius = attrs.pop('radius', 10) result = [ htmltag(tagname, {'class': 'rounded'}, **attrs), markup, Html('<div class="top-left radius-%s"></div>\n' '<div class="top-right radius-%s"></div>\n' '<div class="bottom-left radius-%s"></div>\n' '<div class="bottom-right radius-%s"></div>\n' '</%s>') % (radius, radius, radius, radius, tagname)] return Html('\n').join(result)
def table(form): result = [] for f in form.fields: classes = f.__class__.__name__.lower() + '-field-row' if f.error_text: classes += ' has-error' result.extend((Html('\n<tr class="%s">\n<th>' % classes), f.label, Html('</th>\n<td>'), f.tag)) error = f.error if error: result.append(error) result.append(Html('</td></tr>')) return htmljoin(result)
def __unicode__(form): if form.buttons_align is None: buttons = Html( '\n<tr><td> </td><td>%s</td></tr>') % form.buttons else: buttons = Html('\n<tr><td colspan="2">%s</td></tr>') % form.buttons return htmljoin([ form.header, form.error, Html('\n<table>'), form.table, buttons, Html('\n</table>\n'), form.footer, Html('\n') ])
def blueprint_link(column_count=24, column_width=30, gutter_width=10, ns=''): if column_count == 24 and column_width == 30 and gutter_width == 10 and ns == '': return Html( '<link rel="stylesheet" href="/pony/static/blueprint/screen.css" type="text/css" media="screen, projection">\n' '<link rel="stylesheet" href="/pony/static/blueprint/print.css" type="text/css" media="print">\n' '<!--[if IE]><link rel="stylesheet" href="/pony/static/blueprint/ie.css.css" type="text/css" media="screen, projection"><![endif]-->\n' ) if not ns: params = Html('%s/%s/%s') % (column_count, column_width, gutter_width) else: params = Html('%s/%s/%s/%s') % (column_count, column_width, gutter_width, ns) return Html( '<link rel="stylesheet" href="/pony/static/blueprint/%s/screen.css" type="text/css" media="screen, projection">\n' '<link rel="stylesheet" href="/pony/static/blueprint/%s/print.css" type="text/css" media="print">\n' '<!--[if IE]><link rel="stylesheet" href="/pony/static/blueprint/%s/ie.css.css" type="text/css" media="screen, projection"><![endif]-->\n' ) % (params, params, params)
def markdown(s): from pony.templating import Html, quote from pony.thirdparty.markdown import markdown s = quote(s)[:] result = markdown(s, html4tags=True) result = nbsp_re.sub(r" \1 ", result) return Html(result)
def buttons(form): if not form.submit_fields: return '' result = [htmltag('div', _class='buttons', align=form.buttons_align)] buttons = [f.html for f in form.submit_fields] result.extend(buttons) result.append(Html('\n</div>')) return htmljoin(result)
def normalize_result(result, headers): if hasattr(result, 'read'): content = result # file-like object else: content = tostring(result) headers = dict([(name.replace('_', '-').title(), str(value)) for name, value in headers.items()]) media_type = headers.pop('Type', None) charset = headers.pop('Charset', None) content_type = headers.get('Content-Type') if content_type: media_type, type_params = cgi.parse_header(content_type) charset = type_params.get('charset', 'iso-8859-1') else: if media_type is None: media_type = getattr(result, 'media_type', None) if media_type is None: if isinstance(content, (Html, StrHtml)): media_type = 'text/html' else: media_type = 'text/plain' if charset is None: charset = getattr(result, 'charset', 'UTF-8') content_type = '%s; charset=%s' % (media_type, charset) headers['Content-Type'] = content_type if hasattr(content, 'read') \ or media_type != 'text/html' \ or isinstance(content, (Html, StrHtml)): pass elif isinstance(content, unicode): content = Html(content) elif isinstance(content, str): content = StrHtml(content) else: assert False # pragma: no cover return content, headers
def link(*args, **kwargs): if not args: raise TypeError( 'link() function requires at least one positional argument') attrs = None last = args[-1] if isinstance(last, BoundMarkup): description = last() args = (description, ) + args[:-1] first = args[0] if hasattr(first, 'routes'): func = first args = args[1:] if func.__doc__ is None: description = func.__name__ else: description = Html(func.__doc__.split('\n', 1)[0]) elif len(args) > 1 and hasattr(args[1], 'routes'): description = tostring(first) func = args[1] args = args[2:] elif len(args) > 2 and hasattr(args[2], 'routes'): attrs = args[1] if isinstance(attrs, basestring): attrs = {'class': attrs} elif not hasattr(attrs, 'items'): raise TypeError('Invalid second argument of link() function: %r' % second) description = tostring(first) func = args[2] args = args[3:] elif isinstance(first, basestring): func = link_funcs.get(first) if func is not None: return func(*args[1:], **kwargs) if first.endswith('.css'): if kwargs: raise TypeError('Unexpected key arguments') return css_link(args) if first.endswith('.js'): if len(args) > 1: raise TypeError('Unexpected positional arguments') if kwargs: raise TypeError('Unexpected key arguments') return script_link(first) raise TypeError('Invalid arguments of link() function') href = url(func, *args, **kwargs) return htmljoin( [htmltag('a', attrs, href=href), description, Html('</a>')])
def postprocess(content, stylesheets, component_stylesheets, scripts): assert isinstance(content, basestring) if isinstance(content, (Html, StrHtml)): pass elif isinstance(content, str): content = StrHtml(content) elif isinstance(content, unicode): content = Html(content) if not stylesheets: stylesheets = options.STD_STYLESHEETS base_css = css_links(stylesheets) if base_css: base_css += StrHtml('\n') component_css = css_links(component_stylesheets) if component_css: component_css += StrHtml('\n') scripts = script_links(scripts) if scripts: scripts += StrHtml('\n') doctype = '' try: match = element_re.search(content) if match is None or match.group(2).lower() not in header_tags: doctype = StrHtml(options.STD_DOCTYPE) head = '' body = content else: first_element = match.group(2).lower() for match in element_re.finditer(content): element = match.group(2).lower() if element not in header_tags: break last_match = match bound = last_match.end(1) head = content.__class__(content[:bound]) body = content.__class__(content[bound:]) if first_element in ('!doctype', 'html'): raise _UsePlaceholders doctype = StrHtml(options.STD_DOCTYPE) match = element_re.search(body) if match is None or match.group(2).lower() != 'body': if 'blueprint' in base_css: body = StrHtml('<div class="container">\n%s\n</div>\n') % body body = StrHtml('<body>\n%s</body>') % body match = element_re.search(head) if match is not None and match.group(2).lower() == 'head': raise _UsePlaceholders if css_re.search(head) is not None: base_css = '' head = StrHtml( '<head>' ) + favicon_links + base_css + head + component_css + scripts + StrHtml( '</head>') except _UsePlaceholders: head = head.replace(options.BASE_STYLESHEETS_PLACEHOLDER, base_css, 1) head = head.replace(options.COMPONENT_STYLESHEETS_PLACEHOLDER, component_css, 1) head = head.replace(options.SCRIPTS_PLACEHOLDER, scripts, 1) head = content.__class__(head) if doctype: return StrHtml('\n').join([doctype, head, body]) else: return StrHtml('\n').join([head, body])
def tag(field): result = [htmltag('div', field.attrs, _class='checkboxes')] selection = field.value for value, description, key in field.options: result.append(Html('<div class="checkboxgroup-item">')) result.append( htmltag('input', name=field.name, type='checkbox', value=value, checked=(value in selection))) result.append( Html('<span class="value">%s</span></div>') % description) result.append(Html('</div>')) result.append( htmltag('input', name='.' + field.name, type='hidden', value='')) return htmljoin(result)
def tag(field): result = [htmltag('div', field.attrs, _class='radiobuttons')] selected = field.value for value, description, key in field.options: result.append(Html('<div class="radiobutton">')) result.append( htmltag('input', type='radio', name=field.name, value=key, checked=(value == selected))) result.append( Html('<span class="value">%s</span></div>') % description) result.append(Html('</div>')) result.append( htmltag('input', name='.' + field.name, type='hidden', value='')) return htmljoin(result)
def hidden(grid): result = [ htmltag('input', name='.' + grid.name, type='hidden', value='') ] for row in grid._rows: for field in row: hidden = getattr(field, 'hidden', None) if hidden: result.append(hidden) return Html('\n').join(result)
def tag(field): # for Select and MultiSelect result = [ htmltag('select', field.attrs, name=field.name, multiple=isinstance(field, MultiSelect)) ] value = field.value if isinstance(field, MultiSelect): selection = value elif value is None: selection = set() else: selection = set((value, )) for value, description, key in field.options: if key == description: key = None result.append( htmltag('option', selected=(value in selection), value=key)) result.append(description) result.append(Html('</option>')) result.append(Html('</select>')) return htmljoin(result)
def tag(grid): result = [Html('\n<table><tr>')] for column in grid.columns: result.append(Html('<th>%s</th>') % column) result.append(Html('</tr>\n')) for row, row_class in izip(grid._rows, cycle(('odd', 'even'))): result.append(Html('<tr class="%s">') % row_class) for field in row: if field is None: result.append(Html('<td> </td>')) else: result.append(Html('<td>%s</td>') % field.tag) result.append(Html('</tr>\n')) result.append(Html('</table>\n')) return htmljoin(result)
def img(*args, **kwargs): description = None if isinstance(args[0], basestring): description = args[0] func = args[1] args = args[2:] else: func = args[0] args = args[1:] if func.__doc__ is None: description = func.__name__ else: description = Html(func.__doc__.split('\n', 1)[0]) href = url(func, *args, **kwargs) return img_template % (href, description, description)
def tag(composite): result = [Html('\n<table><tr>')] if composite.show_headers: for i, field in enumerate(composite.fields): if isinstance(field, Submit): label = Html(' ') else: label = field._get_label(colon=False) result.append(Html('<th>%s</th>') % label) result.append(Html('</tr>\n<tr>')) for i, field in enumerate(composite.fields): result.append(Html('<td>%s</td>') % field.tag) result.append(Html('\n</tr></table>\n')) return htmljoin(result)
def footer(form): return Html('</form>')
def tag(field): return Select.tag.fget(field) + Html( '\n<noscript>\n' '<input type="submit" value="apply">\n' '</noscript>\n')
def tag(field): result = [htmltag('textarea', field.attrs, name=field.name)] if field.value is not None: result.append(field.value) result.append(Html('</textarea>')) return htmljoin(result)
def __unicode__(field): return Html('<strong>%s</strong>') % field.value
def error(field): error_text = field.error_text if not error_text: return '' return Html('<div class="error">%s</div>') % error_text
def error(composite): error_text = composite.error_text if not error_text: return '' error_lines = error_text.split('\n') return Html('<div class="error">%s</div>' % Html('<br>\n').join(error_lines))
def jquery_link(): return Html('<script src="/pony/static/jquery/jquery.js"></script>')
def error(form): error_text = form.error_text if not error_text: return '' return Html('\n<div class="error">%s</div>' % error_text)
(?: '''(?:[^\\]|\\.)*?(?:'''|\Z) # '''triple-quoted string''' | \"""(?:[^\\]|\\.)*?(?:\"""|\Z) # \"""triple-quoted string\""" | '(?:[^'\\]|\\.)*?(?:'|$) # 'string' | "(?:[^"\\]|\\.)*?(?:"|$) # "string" )) | ([(,]\s*[A-Za-z_]\w*\s*=) # named argument (group 2) | ([A-Za-z_]\w*(?:\s*\.\s*[A-Za-z_]\w*)*) # identifier chain (group 3) | (\#.*$) # comment (group 4) """, re.VERBOSE) ident_re = re.compile(r'[A-Za-z_]\w*') end1_re = re.compile(r"(?:[^\\]|\\.)*?'''") end2_re = re.compile(r'(?:[^\\]|\\.)*?"""') ident_html = Html('<span class="ident" title="%s">%s</span>') keyword_html = Html('<strong>%s</strong>') comment_html = Html('<span class="comment">%s</span>') str_html = Html('<span class="string">%s</span>') syntax_error_html = Html('<span class="syntax-error">%s</span>') def parse_line(line): pos = 0 stop = len(line) while pos < stop: match = python_re.search(line, pos) if match is None: break start, end = match.span() yield 'other', pos, start, line[pos:start] i = match.lastindex
if kwargs: raise TypeError('Unexpected key arguments') return css_link(args) if first.endswith('.js'): if len(args) > 1: raise TypeError('Unexpected positional arguments') if kwargs: raise TypeError('Unexpected key arguments') return script_link(first) raise TypeError('Invalid arguments of link() function') href = url(func, *args, **kwargs) return htmljoin( [htmltag('a', attrs, href=href), description, Html('</a>')]) img_template = Html(u'<img src="%s" title="%s" alt="%s">') def img(*args, **kwargs): description = None if isinstance(args[0], basestring): description = args[0] func = args[1] args = args[2:] else: func = args[0] args = args[1:] if func.__doc__ is None: description = func.__name__ else: description = Html(func.__doc__.split('\n', 1)[0]) href = url(func, *args, **kwargs) return img_template % (href, description, description)