def render_plugins(context, plugins):
"""
Render a list of plugins. Requires the
:class:`feincms3.renderer.TemplatePluginRenderer` instance in the context
as ``renderer``::
{% render_plugins plugins %}
This plugin is equivalent to::
{% for plugin in plugins %}{% render_plugin plugin %}{% endfor %}
In general you should prefer
:func:`~feincms3.templatetags.feincms3_renderer.render_region` over this
tag.
"""
renderer = context['renderer']
return mark_safe(''.join(
renderer.render_plugin_in_context(plugin, context)
for plugin in plugins
))
python类mark_safe()的实例源码
def indented_title(self, instance):
"""
Use Unicode box-drawing characters to visualize the tree hierarchy.
"""
box_drawing = []
for i in range(instance.depth - 2):
box_drawing.append('<i class="l"></i>')
if instance.depth > 1:
box_drawing.append('<i class="a"></i>')
return format_html(
'<div class="box">'
'<div class="box-drawing">{}</div>'
'<div class="box-text" style="text-indent:{}px">{}</div>'
'</div>',
mark_safe(''.join(box_drawing)),
(instance.depth - 1) * 30,
instance,
)
def render(self, region, context, timeout=None):
"""render(self, region, context, *, timeout=None)
Render a single region using the context passed
If ``timeout`` is ``None`` caching is disabled.
.. note::
You should treat anything except for the ``region`` and ``context``
argument as keyword-only.
"""
if timeout is not None:
key = self.cache_key(region)
html = cache.get(key)
if html is not None:
return html
html = mark_safe(''.join(
self._renderer.render_plugin_in_context(plugin, context)
for plugin in self._contents[region]
))
if timeout is not None:
cache.set(key, html, timeout=timeout)
return html
def kolibri_language_globals(context):
lang_dir = "rtl" if get_language_bidi() else "ltr"
js = """
<script>
var languageCode = '{lang_code}';
var languageDir = '{lang_dir}';
var languages = JSON.parse('{languages}');
</script>
""".format(
lang_code=get_language(),
lang_dir=lang_dir,
languages=json.dumps({code: {
# Format to match the schema of the content Language model
'id': code,
'lang_name': name,
'lang_direction': get_language_info(code)['bidi']
} for code, name in settings.LANGUAGES}),
)
return mark_safe(js)
def get_extra_event_management_html(self, event):
if event.source_json_data:
json_data = json.loads(event.source_json_data)
hosts = json_data.get('hosts')
additional_hosts = []
if hosts:
for hostpk, host in hosts.items():
if int(hostpk) not in self.ignore_hosts\
and (not event.organization_host_id\
or hostpk != event.organization_host.member_system_pk):
additional_hosts.append(host)
if additional_hosts:
return mark_safe(
'<div><b>Additional Hosts:</b>'
+ ''.join([
format_html('<span data-pk="{}">{}</span>', h['member_system_pk'], h['name'])
for h in additional_hosts])
+ '</div>')
return None
def get_results_from_search_response(response):
parsed = response.json()
formatted_results = []
for result in parsed['hits']['hits']:
formatted = format_company_details(result['_source'])
if 'highlight' in result:
highlighted = '...'.join(
result['highlight'].get('description', '') or
result['highlight'].get('summary', '')
)
# escape all html tags other than <em> and </em>
highlighted_escaped = (
escape(highlighted)
.replace('<em>', '<em>')
.replace('</em>', '</em>')
)
formatted['highlight'] = mark_safe(highlighted_escaped)
formatted_results.append(formatted)
parsed['results'] = formatted_results
return parsed
def field_choices(self, field, request, model_admin):
mptt_level_indent = getattr(model_admin, 'mptt_level_indent', self.mptt_level_indent)
language_bidi = get_language_bidi()
initial_choices = field.get_choices(include_blank=False)
pks = [pk for pk, val in initial_choices]
models = field.related_model._default_manager.filter(pk__in=pks)
levels_dict = {model.pk: getattr(model, model._mptt_meta.level_attr) for model in models}
choices = []
for pk, val in initial_choices:
padding_style = ' style="padding-%s:%spx"' % (
'right' if language_bidi else 'left',
mptt_level_indent * levels_dict[pk])
choices.append((pk, val, mark_safe(padding_style)))
return choices
# Ripped from contrib.admin.filters,RelatedFieldListFilter Django 1.8 to
# yield padding_style
def html_full_contact(self):
parts = []
if self.contact_name and self.contact_email:
parts.append(format_html(
'{name} <<a href="mailto:{email}">{email}</a>>',
name=self.contact_name,
email=self.contact_email
))
elif self.contact_name:
parts.append(self.contact_name)
elif self.contact_email:
parts.append(format_html('<a href="mailto:{email}">{email}</a>', email=self.contact_email))
if self.contact_phone and not self.contact_hide_phone:
parts.append(self.contact_phone)
if parts:
return format_html_join(mark_safe(" — "), '{}', ((part,) for part in parts))
else:
return format_html("<em>{}</em>", _("Pas d'informations de contact"))
def as_p(self):
retval = super(AddSpacersMixin, self).as_p()
if self.add_spacers:
# Hack to help test interacting with elements
# that aren't in view.
retval = mark_safe(retval.replace('</p>', '</p>' + ('<br>' * 100)))
return retval
def indent(self, depth):
return mark_safe('├' * (depth - 1))
def register_string_renderer(self, plugin, renderer):
"""
Register a rendering function which is passed the plugin instance and
returns a HTML string::
renderer.register_string_renderer(
RichText,
lambda plugin: mark_safe(plugin.text),
)
"""
self._renderers[plugin] = (None, renderer)
def render_html(plugin, **kwargs):
"""
Return the HTML code as safe string so that it is not escaped. Of course
the contents are not guaranteed to be safe at all
"""
return mark_safe(plugin.html)
def render_richtext(plugin, **kwargs):
"""
Return the text of the rich text plugin as a safe string (``mark_safe``)
"""
return mark_safe(plugin.text)
def dict_to_json(pydict):
"""
Accepts a python dict and returns it's JSON representation.
Sample usage::
<script type="application/ld+json">
{% dict_to_json some_dict %}
</script>
"""
return mark_safe(json.dumps(pydict))
def inline_static_file(path, minify=None):
"""
Outputs the [minified] contents of a given static file.
For example, to display the minified CSS file "``inline.css``"::
<style>
{% inline_static_file 'inline.css' 'css' %}
</style>
The optional ``minify`` argument can be one of css, js, or html.
"""
p = finders.find(path)
if not p:
raise RuntimeError('path=%s not found' % path)
elif os.path.isdir(p):
raise RuntimeError('path=%s is not a file' % path)
with open(p, encoding='utf-8') as f:
if minify == 'js':
return mark_safe(js_minify(f.read()))
elif minify == 'css':
return mark_safe(css_minify(f.read()))
elif minify == 'html':
return mark_safe(html_minify(f.read()))
else:
return mark_safe(f.read())
def autofocus_form(form, *args, **kwargs):
"""
Add the 'autofocus' attribute to the first input tag of a form.
Usage::
{% autofocus_form form form_group_class='row' %}
Extra args and kwargs are passed to ``bootstrap_form``.
"""
return mark_safe(re.sub(
'<input', '<input autofocus',
str(bootstrap_form(form, *args, **kwargs)),
count=1
))
def autofocus_field(field, *args, **kwargs):
"""
Add the 'autofocus' attribute to an input tag.
Usage::
{% autofocus_field field field_class='col-md-12' %}
Extra args and kwargs are passed to ``bootstrap_field``.
"""
return mark_safe(re.sub(
'<input', '<input autofocus',
str(bootstrap_field(field, *args, **kwargs)),
count=1
))
def minify_js(value):
return mark_safe(js_minify(value))
def minify_html(value):
return mark_safe(html_minify(value))
def make_script_vars(self, name):
context = self.process_croppie_context(name)
vars = 'var croppieFieldName = "{}"\n var croppieOptions = {}' \
.format(
context['croppie_field_name'],
context['croppie_options'],
)
return mark_safe(vars)
def editor_css():
return mark_safe(
'''
<style>
.highlight-red { background: red; color: white; }
.highlight-yellow { background: yellow; color: black; }
.highlight-red { background: gray; color: red; }
</style>
''')
def markdown_to_html(md):
html = markdown(md)
allowed_tags = bleach.ALLOWED_TAGS + ['p', 'pre', 'span' ] + ['h%d' % i for i in range(1, 7) ]
html = bleach.clean(html, tags=allowed_tags)
return mark_safe(html)
def render(self, data, accepted_media_type=None, renderer_context=None):
codec = coreapi.codecs.CoreJSONCodec()
schema = base64.b64encode(codec.encode(data))
template = loader.get_template(self.template)
context = {'schema': mark_safe(schema)}
request = renderer_context['request']
return template_render(template, context, request=request)
def angular_model(model, angular_model_name, extra_params={}):
""" Returns javascript that preprocesses obj before attaching it to window
where angular controller can grab it """
ret = "<script>\n"
if model is None:
ret += "window.%s = {};\n" % (angular_model_name)
else:
# cast foreign key and m2m fields to be strings
json_ret = model.to_json()
model_dict = json.loads(json_ret)
fk_fields = model.get_foreign_key_fields()
m2m_fields = model.get_many_to_many_fields()
for field, val in model_dict["fields"].iteritems():
if field in fk_fields:
model_dict["fields"][field] = str(val)
if field in m2m_fields:
model_dict["fields"][field] = map(str, val)
ret += "window.%s = %s;\n" % (angular_model_name, json.dumps(model_dict, sort_keys=True))
# adds converter for datetime fields
for field in model.READABLE_ATTRS(type_filter=models.DateField):
# DateTimeFields are instances of DateFields
ret += ("window.%s.fields.%s = new Date(window.%s.fields.%s);\n" %
(angular_model_name, field, angular_model_name, field))
# date_fields = model.WRITEABLE_ATTRS(type_filter=models.DateField, type_exclude=models.DateTimeField)
# date_fields = json.dumps(date_fields)
# ret += "window.%s.date_fields = %s" % (angular_model_name, date_fields)
ret += "</script>\n"
return mark_safe(ret)
def to_json(data):
return mark_safe(JSONRenderer().render(data).decode('utf-8'))
def contact_info_to_html(contact_info_dict):
phone = contact_info_dict.get('sms', '')
if phone:
phone = format_phone_number(phone)
email = contact_info_dict.get('email', '')
html = oxford_comma([
thing for thing in (phone, email) if thing])
return mark_safe(html)
def render(self, name, value, attrs=None, choices=()):
widget_ = super(MultiuploadWidget, self).render(name, value, attrs)
output = '<div id="hidden_container" style="display:none;">%s</div>' % widget_
return mark_safe(output)
def kolibri_main_navigation():
"""
A tag to include an initial JS-object to bootstrap data into the app.
:return: An html string
"""
init_data = {
'nav_items': [],
'user_nav_items': [],
}
for hook in NavigationHook().registered_hooks:
init_data['nav_items'].append({
'text': str(hook.label),
'url': str(hook.url),
})
for hook in UserNavigationHook().registered_hooks:
init_data['user_nav_items'].append({
'text': str(hook.label),
'url': str(hook.url),
})
html = ("<script type='text/javascript'>"
"window._nav={0};"
"</script>".format(json.dumps(init_data)))
return mark_safe(html)
def kolibri_set_urls(context):
js_global_object_name = getattr(settings, 'JS_REVERSE_JS_GLOBAL_OBJECT_NAME', JS_GLOBAL_OBJECT_NAME)
js_var_name = getattr(settings, 'JS_REVERSE_JS_VAR_NAME', JS_VAR_NAME)
js = (js_reverse_inline(context) +
"Object.assign({0}.urls, {1}.{2})".format(settings.KOLIBRI_CORE_JS_NAME,
js_global_object_name,
js_var_name))
return mark_safe(js)
def kolibri_set_server_time():
html = ("<script type='text/javascript'>"
"{0}.utils.serverClock.setServerTime({1});"
"</script>".format(settings.KOLIBRI_CORE_JS_NAME,
json.dumps(now(), cls=DjangoJSONEncoder)))
return mark_safe(html)