本文整理汇总了Python中webhelpers.html.literal函数的典型用法代码示例。如果您正苦于以下问题:Python literal函数的具体用法?Python literal怎么用?Python literal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了literal函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _generate_fields
def _generate_fields(self, request, fields_list, override_data):
html = []
for name in fields_list['fields']:
field = self._fields[name]
values = {'with_tip':self._params.get('with_tip', True)}
values.update(field)
data = override_data.get(name, {})
values.update(data)
values.pop('validator', None)
input = InputField(name=name, **values)
html.append(input(request))
# Don't show empty fieldsets
if not html:
return ''
title = fields_list.get('name', '')
template_path = request.registry.settings.get(
'pyramid_webforms.fieldset_tpl',
'pyramid_webforms:templates/fieldset.p_wf_mako'
)
return literal(
render(
template_path,
{
'fieldset_title': title,
'fieldset_fields': literal(''.join(html))
},
request
)
)
示例2: __unicode__
def __unicode__(self):
# unbound forms should return the HTML unmodified. If this was passed
# through htmlfill instead, all form values would be nuked.
try:
response_charset = response.determine_charset()
except TypeError: # no pylons request is active
response_charset = 'utf-8'
if not self.is_bound:
defaults = self.initial.copy()
# using WebHelpers, boolean values cannot be True; they must be '1'
for key, value in defaults.items():
if value is True:
defaults[key] = '1'
return literal(formencode.htmlfill.render(
form=self.html,
defaults=defaults,
errors=self.errors,
encoding=response_charset # use the proper charset
))
else:
defaults = self.data.copy()
# using WebHelpers, boolean values cannot be True; they must be '1'
for key, value in defaults.items():
if value is True:
defaults[key] = '1'
return literal(formencode.htmlfill.render(
form=self.html,
defaults=defaults,
errors=self.errors,
encoding=response_charset # use the proper charset
))
示例3: build_paginator
def build_paginator(self, current_page, total_pages, base_url, query):
next = current_page + 1
prev = current_page - 1
rand = random.randint(1, total_pages)
at_start = (current_page <= 1 or total_pages <= 1)
at_end = current_page >= total_pages
first_html = "First" if at_start else self.gen_page_link(base_url, query, 1, "First")
prev_html = "Prev" if at_start else self.gen_page_link(base_url, query, prev, "Prev")
random_html = self.gen_page_link(base_url, query, rand, "Random")
next_html = "Next" if at_end else self.gen_page_link(base_url, query, next, "Next")
last_html = "Last" if at_end else self.gen_page_link(base_url, query, total_pages, "Last")
start = max(current_page - 5, 1)
end = min(start+10, total_pages)
pages = []
for n in range(start, end):
pages.append(self.gen_page_link_block(base_url, query, n, current_page, str(n)))
return (
literal(" | ").join([first_html, prev_html, random_html, next_html, last_html]) +
literal("<br>") +
literal(" | ").join(pages)
)
示例4: add_auto_html_headers
def add_auto_html_headers(self):
# 404/static handler will map these to themes/foo/bar.ico or lib/static/bar.ico
self.add_html_header(literal("<link rel='icon' type='image/x-icon' href='/favicon.ico'>"))
self.add_html_header(literal("<link rel='apple-touch-icon' href='/apple-touch-icon.png'>"))
theme = context.config.get("theme", "default")
# TODO: concatenate files
for css in (
glob("shimpy/static/*.css") +
glob("shimpy/ext/*/style.css") +
glob("shimpy/theme/%s/*.css" % theme)
):
mtime = os.stat(css).st_mtime
css = css.replace("shimpy/static/", "")
css = css.replace("shimpy/theme/%s/" % theme, "")
self.add_html_header(literal("<link rel='stylesheet' href='/static/%s?ts=%d' type='text/css'>") % (css, mtime))
for js in (
glob("shimpy/static/*.js") +
glob("shimpy/ext/*/script.css") +
glob("shimpy/theme/%s/script.js" % theme)
):
mtime = os.stat(js).st_mtime
js = js.replace("shimpy/static/", "")
js = js.replace("shimpy/theme/%s/" % theme, "")
self.add_html_header(literal("<script src='/static/%s?ts=%d'></script>") % (js, mtime))
示例5: render_body
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
capture = context.get('capture', UNDEFINED)
c = context.get('c', UNDEFINED)
self = context.get('self', UNDEFINED)
__M_writer = context.writer()
# SOURCE LINE 1
__M_writer(u'\n\n')
# SOURCE LINE 3
__M_writer(u'\n')
# SOURCE LINE 4
__M_writer(u'\n\n')
# SOURCE LINE 6
__M_writer(escape(literal(c.page.content)))
__M_writer(u'\n\n')
# SOURCE LINE 17
__M_writer(u'\n\n')
# SOURCE LINE 22
__M_writer(u'\n\n')
# SOURCE LINE 24
if c.available_tags:
# SOURCE LINE 25
__M_writer(escape(literal(htmlfill.render(capture(self.tags, c.available_tags), c.selected_tags))))
__M_writer(u'\n')
# SOURCE LINE 27
__M_writer(u'\n')
# SOURCE LINE 52
__M_writer(u'\n')
return ''
finally:
context.caller_stack._pop_frame()
示例6: _make_menu_item_handling_many_package_types
def _make_menu_item_handling_many_package_types(menu_item, title, **kw):
# See ckan/lib/helpers.py:545
_menu_items = config['routes.named_routes']
if menu_item not in _menu_items:
raise Exception('menu item `%s` cannot be found' % menu_item)
item = copy.copy(_menu_items[menu_item])
item.update(kw)
active = h._link_active(item)
if c.controller == 'package' and len(menu_item) > 7:
# Guess type of package
if request.path == '/':
type = 'dataset'
else:
parts = [x for x in request.path.split('/') if x]
if len(parts[0]) == 2: # is it locale? simple check
type = parts[1]
else:
type = parts[0]
active = type == menu_item[:-7] # assuming menu_item == '<type>_search'
needed = item.pop('needed')
for need in needed:
if need not in kw:
raise Exception('menu item `%s` need parameter `%s`'
% (menu_item, need))
link = h._link_to(title, menu_item, suppress_active_class=True, **item)
if active:
return literal('<li class="active">') + link + literal('</li>')
return literal('<li>') + link + literal('</li>')
示例7: aloha_editable_attribute
def aloha_editable_attribute(request, obj, attr):
val = getattr(obj, attr, '')
pk_id = getattr(obj, obj.__pk__, '')
if is_crm_logged_in(request):
editable_id = '%s%s' % (obj.__pk__, attr)
val = unicodedata.normalize('NFKD', val).encode('ascii','ignore') if val else ''
return literal("""
<div id="editable_{editable_id}">
{val}
</div>
<input type="hidden" id="editable_{editable_id}_type" value="attribute"/>
<input type="hidden" id="editable_{editable_id}_objtype" value="{objtype}"/>
<input type="hidden" id="editable_{editable_id}_module" value="{module}"/>
<input type="hidden" id="editable_{editable_id}_attr" value="{attr}"/>
<input type="hidden" id="editable_{editable_id}_pk_id" value="{pk_id}"/>
<script type="text/javascript">
Aloha.ready( function() {{
Aloha.jQuery('#editable_{editable_id}').aloha();
Aloha.bind('aloha-editable-deactivated', pvs_aloha_onsave);
}} );
</script>""".format(editable_id=editable_id,
pk_id=pk_id,
module=obj.__module__,
attr=attr,
objtype=obj.__class__.__name__,
val=literal(str(val))))
else:
return literal(val)
示例8: render_template
def render_template():
globs = extra_vars or {}
globs.update(pylons_globals())
globs['actions'] = model.Action
# Using pylons.url() directly destroys the localisation stuff so
# we remove it so any bad templates crash and burn
del globs['url']
try:
template_path, template_type = render_.template_info(template_name)
except render_.TemplateNotFound:
template_type = 'genshi'
template_path = ''
# snippets should not pass the context
# but allow for legacy genshi templates
if renderer == 'snippet' and template_type != 'genshi':
del globs['c']
del globs['tmpl_context']
log.debug('rendering %s [%s]' % (template_path, template_type))
if config.get('debug'):
context_vars = globs.get('c')
if context_vars:
context_vars = dir(context_vars)
debug_info = {'template_name': template_name,
'template_path': template_path,
'template_type': template_type,
'vars': globs,
'c_vars': context_vars,
'renderer': renderer}
if 'CKAN_DEBUG_INFO' not in request.environ:
request.environ['CKAN_DEBUG_INFO'] = []
request.environ['CKAN_DEBUG_INFO'].append(debug_info)
# Jinja2 templates
if template_type == 'jinja2':
# We don't want to have the config in templates it should be
# accessed via g (app_globals) as this gives us flexability such
# as changing via database settings.
del globs['config']
# TODO should we raise error if genshi filters??
return render_jinja2(template_name, globs)
# Genshi templates
template = globs['app_globals'].genshi_loader.load(
template_name.encode('utf-8'), cls=loader_class
)
stream = template.generate(**globs)
for item in p.PluginImplementations(p.IGenshiStreamFilter):
stream = item.filter(stream)
if loader_class == NewTextTemplate:
return literal(stream.render(method="text", encoding=None))
return literal(stream.render(method=method, encoding=None,
strip_whitespace=True))
示例9: gravatar
def gravatar(email, _class=None, size=48, default_type='identicon'):
if _class:
return literal('<img src="' + \
get_gravatar_url(email, size, default_type) + \
'" class="' + _class + '" />')
else:
return literal('<img src="' + \
get_gravatar_url(email, size, default_type) + '" />')
示例10: display_page
def display_page(self, page, image, parts):
page.heading = " ".join([t.name for t in image.tags])
page.title = "Image %d: %s" % (image.id, page.heading)
page.add_html_header(literal("<meta name=\"keywords\" content=\"%s\">") % image.tags_plain_text.replace(" ", ", "))
page.add_html_header(literal("<meta property=\"og:title\" content=\"%s\">") % image.title)
page.add_html_header(literal("<meta property=\"og:type\" content=\"article\">"))
page.add_html_header(literal("<meta property=\"og:image\" content=\"%s\">") % image.thumb_url)
page.add_html_header(literal("<meta property=\"og:url\" content=\"%s\">") % image.page_url)
示例11: _SI_number_span_close
def _SI_number_span_close(number):
''' outputs a span with the number in SI unit eg 14700 -> 14.7k '''
number = int(number)
if number < 1000:
output = literal('<span>')
else:
output = literal('<span title="' + formatters.localised_number(number) + '">')
return output + formatters.localised_SI_number(number) + literal('</span>')
示例12: SI_number_span
def SI_number_span(number):
""" outputs a span with the number in SI unit eg 14700 -> 14.7k """
number = int(number)
if number < 1000:
output = literal("<span>")
else:
output = literal('<span title="' + formatters.localised_number(number) + '">')
return output + formatters.localised_SI_number(number) + literal("</span>")
示例13: render_template
def render_template():
globs = extra_vars or {}
globs.update(pylons_globals())
globs["actions"] = model.Action
# Using pylons.url() directly destroys the localisation stuff so
# we remove it so any bad templates crash and burn
del globs["url"]
try:
template_path, template_type = lib.render.template_info(template_name)
except lib.render.TemplateNotFound:
template_type = "genshi"
template_path = ""
# snippets should not pass the context
# but allow for legacy genshi templates
if renderer == "snippet" and template_type != "genshi":
del globs["c"]
del globs["tmpl_context"]
log.debug("rendering %s [%s]" % (template_path, template_type))
if config.get("debug"):
context_vars = globs.get("c")
if context_vars:
context_vars = dir(context_vars)
debug_info = {
"template_name": template_name,
"template_path": template_path,
"template_type": template_type,
"vars": globs,
"c_vars": context_vars,
"renderer": renderer,
}
if "CKAN_DEBUG_INFO" not in request.environ:
request.environ["CKAN_DEBUG_INFO"] = []
request.environ["CKAN_DEBUG_INFO"].append(debug_info)
# Jinja2 templates
if template_type == "jinja2":
# We don't want to have the config in templates it should be
# accessed via g (app_globals) as this gives us flexability such
# as changing via database settings.
del globs["config"]
# TODO should we raise error if genshi filters??
return render_jinja2(template_name, globs)
# Genshi templates
template = globs["app_globals"].genshi_loader.load(template_name, cls=loader_class)
stream = template.generate(**globs)
for item in PluginImplementations(IGenshiStreamFilter):
stream = item.filter(stream)
if loader_class == NewTextTemplate:
return literal(stream.render(method="text", encoding=None))
return literal(stream.render(method=method, encoding=None, strip_whitespace=True))
示例14: __call__
def __call__(self, request, name=None, value=None, selected=None,
title=None, tip=None, data=None, **kwargs):
# self.kw is global so we need thread-local kw dictionary here
kw = {}
if data is None:
data = {}
if title is None:
title = self.title
if tip is None:
tip = self.tip
if self.type == 'html':
input = value or self.value
else:
kw.update(self.kw)
kw.update(**data)
if name is None:
name = self.name
kwargs = self.__getattribute__('_prepare_{}'.format(self.type))()
with_tip = self.kw.get('with_tip', kwargs.get('with_tip', True))
kwargs['class_'] = '{var}{const}'.format(
var=kwargs.get('class_', self.type),
const=(with_tip and ' with-tip' or '')
)
kwargs.update(self.kw.get('html5_attrs', {}))
input = tags.__dict__[self.tag_type](**kwargs)
extra_html = literal(kw.pop('extra_html', ''))
tip_escape = kw.pop('tip_escape', False)
input_only = kw.pop('input_only', False)
if input_only:
# input is already a literal type
return input
error = request.tmpl_context.form_errors.get(name, '')
if error:
error = field_error(request, error)
template_path = request.registry.settings.get(
'pyramid_webforms.field_tpl',
'pyramid_webforms:templates/field.p_wf_mako'
)
return literal(
render(template_path,
{
'field_name': name,
'field_title': title,
'field_error_message': error,
'field_input': input,
'field_tip': self.tooltip(request, tip, tip_escape),
'field_extras': extra_html
},
request
)
)
示例15: test_lit_re
def test_lit_re():
lit = literal('This is a <string>')
unlit = 'This is also a <string>'
result = lit_sub(r'<str', literal('<b'), lit)
eq_(u'This is a <bing>', escape(result))
result = lit_sub(r'a <str', 'a <b> <b', unlit)
eq_(u'This is also a <b> <bing>', escape(result))