Here are the examples of the python api django.utils.html.format_html taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
173 Examples
4
Example 1
def render(self, name, value, attrs=None, choices=()):
if value is None: value = []
final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
id_ = final_attrs.get('id', None)
inputs = []
for i, v in enumerate(value):
input_attrs = dict(value=force_text(v), **final_attrs)
if id_:
# An ID attribute was given. Add a numeric index as a suffix
# so that the inputs don't all have the same ID attribute.
input_attrs['id'] = '%s_%s' % (id_, i)
inputs.append(format_html('<input{0} />', flatatt(input_attrs)))
return mark_safe('\n'.join(inputs))
4
Example 2
def render_css(self):
# To keep rendering order consistent, we can't just iterate over items().
# We need to sort the keys, and iterate over the sorted list.
media = sorted(self._css.keys())
return chain(*[
[format_html('<link href="{0}" type="text/css" media="{1}" rel="stylesheet" />', self.absolute_path(path), medium)
for path in self._css[medium]]
for medium in media])
4
Example 3
def render(self, name, value, attrs=None):
if value is None: value = ''
final_attrs = self.build_attrs(attrs, name=name)
return format_html('<textarea{0}>\r\n{1}</textarea>',
flatatt(final_attrs),
force_text(value))
3
Example 4
Project: tri.table Source File: __init__.py
def render_cell_contents(self):
cell_contents = self.render_formatted()
url = self.url
if url:
url_title = self.url_title
cell_contents = format_html('<a{}{}>{}</a>',
format_html(' href="{}"', url),
format_html(' title="{}"', url_title) if url_title else '',
cell_contents)
return mark_safe(cell_contents)
3
Example 5
Project: wagtail Source File: wagtail_hooks.py
@hooks.register('insert_editor_js')
def editor_js():
return format_html(
"""
<script src="{0}"></script>
<script>window.chooserUrls.snippetChooser = '{1}';</script>
""",
static('wagtailsnippets/js/snippet-chooser.js'),
urlresolvers.reverse('wagtailsnippets:choose_generic')
)
3
Example 6
def label_tag(self):
attrs = {}
if not self.is_first:
attrs["class"] = "inline"
label = self.field['label']
return format_html('<label{}>{}:</label>',
flatatt(attrs),
capfirst(force_text(label)))
3
Example 7
Project: django-shop Source File: order.py
def get_customer_link(self, obj):
try:
url = reverse('admin:shop_customerproxy_change', args=(obj.customer.pk,))
return format_html('<a href="{0}" target="_new">{1}</a>', url, obj.customer.get_username())
except NoReverseMatch:
return format_html('<strong>{0}</strong>', obj.customer.get_username())
3
Example 8
Project: zulip Source File: deliver_email.py
def get_sender_as_string(dictionary):
# type: (Dict[str, str]) -> str
if dictionary["sender_email"]:
return dictionary["sender_email"] if not dictionary["sender_name"] else format_html(u"\"{0}\" <{1}>",
dictionary["sender_name"],
dictionary["sender_email"])
return settings.DEFAULT_FROM_EMAIL
3
Example 9
Project: SmartElect Source File: libya_bread.py
@property
def vumilog_as_html(self):
"""Return HTML for this instance's linked vumilog that has both a human-readable
display and links to the read views for the vumilog (or "None")."""
if not self.vumi:
return NO_LINKED_OBJECT
return format_html(
ANCHOR_SNIPPET,
self.vumi.get_absolute_url(),
unicode(self.vumi))
3
Example 10
def render(self, name, value, attrs=None):
if value is None:
value = ''
input_attrs = self.build_attrs(attrs, name=name)
canvas_attrs = self.build_attrs(name=name)
if value != '':
# Only add the 'value' attribute if a value is non-empty.
input_attrs['value'] = escape(value).encode('ascii', 'ignore')
return format_html('<div class="gridmanager-widget-wrap"><input{} type="hidden" /><div class="gridmanager-widget-editor"/></div>', flatatt(input_attrs), flatatt(canvas_attrs))
3
Example 11
def render(self, name, value, attrs=None):
if value is None:
html = u"""<paper-input-container label='{0}'>
<label>{0}</label>
<input is="iron-input" name="{0}" type="password"/>
</paper-input-container>"""
return format_html(html, name)
else:
html = u"""<paper-input-container label='{0}' type="password" attr-for-value="value">
<label>{0}</label>
<input is="iron-input" name="{0}" type="password" value="{1}"/>
</paper-input-container>"""
return format_html(html, name, value)
3
Example 12
@register.simple_tag
def pagination_link_previous(current_page, view):
if current_page.has_previous():
previous_page_number0 = current_page.previous_page_number() - 1
return format_html(
'<li class="prev"><a href="%s" class="icon icon-arrow-left">%s'
'</a></li>' %
(view.get_query_string({view.PAGE_VAR: previous_page_number0}),
_('Previous'))
)
return ''
3
Example 13
Project: wagtailmodeladmin Source File: wagtailmodeladmin_tags.py
@register.simple_tag
def pagination_link_next(current_page, view):
if current_page.has_next():
next_page_number0 = current_page.next_page_number() - 1
return format_html(
'<li class="next"><a href="%s" class="icon icon-arrow-right-after">%s</a></li>' %
(view.get_query_string({PAGE_VAR: next_page_number0}), _('Next'))
)
return ''
3
Example 14
def render(self):
template = self.template
if template:
# positional arguments here to get compatibility with both django 1.7 and 1.8+
return render_to_string(template, dict(bound_row=self, row=self.row, table=self.table))
else:
return format_html('<tr{}>{}</tr>', self.render_attrs(), self.render_cells())
3
Example 15
@register.filter(is_safe=True)
@stringfilter
def render_email(value):
if value:
mailbox, domain = value.split('@')
mailbox_tokens = mailbox.split('.')
domain_tokens = domain.split('.')
mailbox = '<span>.</span>'.join(mailbox_tokens)
domain = '<span>.</span>'.join(domain_tokens)
return format_html('<span>@</span>'.join((mailbox, domain)))
return None
3
Example 16
def edit_transaction(self, obj):
if obj.id:
return format_html(
'<a href="/admin/iati/transaction/{}/" onclick="return showAddAnotherPopup(this);">Edit details</a>',
str(obj.id))
else:
return format_html(
'Please save the activity to edit receiver/provider details')
3
Example 17
Project: shuup Source File: toolbar.py
def render(self, request):
# The toolbar is wrapped in a form without an action,
# but `PostActionButton`s use the HTML5 `formaction` attribute.
yield '<div class="shuup-toolbar">'
yield '<form method="POST">'
yield format_html("<input type='hidden' name='csrfmiddlewaretoken' value='{0}'>", get_token(request))
yield '<div class="btn-toolbar" role="toolbar">'
for group in self:
if group:
for bit in group.render(request):
yield bit
yield '</div></form></div>'
3
Example 18
Project: django-dynamic-cabinetmaps Source File: handle.py
def create_cabinet_cells(self, cabinet_num, offset=None):
leadrail = LeadRail()
structure_list = []
for i in xrange(cabinet_num, offset):
structure_list.append(
format_html(self.structure_template.single_cabinet_template, str(i + 1),
mark_safe(leadrail.create_lead_rail_nums(
self.lead_rail_num,
self.structure_template.lead_rail_rows_template
))))
return ''.join(structure_list)
3
Example 19
def contact(self, sponsor):
# comma-separated emails in mailto: should work: https://www.ietf.org/rfc/rfc2368.txt
# but the commas need to be URL-quoted
return format_html(
u'<a href="mailto:{}">{}</a>',
quote(u','.join(sponsor.contact_emails)),
sponsor.contact_name
)
3
Example 20
def render(self, name, value, attrs=None):
# Unlike inputs using paper-input-container directly,
# paper-input does not work out of the box with the native form
# element.
if value is None:
html = u"""<paper-input-container label='{0}' >
<label>{0}</label>
<input is="iron-input" name="{0}" class="paper-input-input">
</paper-input-container>"""
return format_html(html, name)
else:
html = u"""<paper-input-container label='{0}' attr-for-value="value">
<label>{0}</label>
<input is="iron-input" name="{0}" value="{1}">
</paper-input-container>"""
return format_html(html, name, value)
3
Example 21
def build_attrs(self, attrs={}, **kwargs):
to_opts = self.rel.to._meta
if "class" not in attrs:
attrs['class'] = 'select-search'
else:
attrs['class'] = attrs['class'] + ' select-search'
attrs['data-search-url'] = self.admin_view.get_admin_url(
'%s_%s_changelist' % (to_opts.app_label, to_opts.model_name))
attrs['data-placeholder'] = _('Search %s') % to_opts.verbose_name
attrs['data-choices'] = '?'
if self.rel.limit_choices_to:
for i in list(self.rel.limit_choices_to):
attrs['data-choices'] += "&_p_%s=%s" % (i, self.rel.limit_choices_to[i])
attrs['data-choices'] = format_html(attrs['data-choices'])
return super(ForeignKeySearchWidget, self).build_attrs(attrs, **kwargs)
3
Example 22
Project: pycontw2016 Source File: renderers.py
def render_block_location(location):
return format_html(
'<div class="slot-item__label slot-item__label--{key}">'
'{display}</div>',
key=location.split('-', 1)[-1],
display={
Location.ALL: '',
Location.R012: 'R0 R1 R2',
Location.R0: 'R0',
Location.R1: 'R1',
Location.R2: 'R2',
Location.R3: 'R3',
}[location],
)
3
Example 23
def render(self, name, value, attrs=None):
final_attrs = self.build_attrs(attrs, name=name)
output = [format_html('<select{0}>', flatatt(final_attrs))]
if value:
output.append(format_html('<option selected="selected" value="{0}">{1}</option>', value, self.label_for_value(value)))
output.append('</select>')
return mark_safe('\n'.join(output))
3
Example 24
@classmethod
def get_identifier(cls, instance):
identifier = super(ProcessBarPlugin, cls).get_identifier(instance)
num_cols = instance.get_children().count()
content = ungettext_lazy('with {} page', 'with {} pages', num_cols).format(num_cols)
return format_html('{0}{1}', identifier, content)
3
Example 25
Project: django-treebeard Source File: admin_tree.py
@register.simple_tag
def treebeard_css():
"""
Template tag to print out the proper <link/> tag to include a custom .css
"""
css_file = urljoin(get_static_url(), 'treebeard/treebeard-admin.css')
return format_html(
"""<link rel="stylesheet" type="text/css" href="{}"/>""",
mark_safe(css_file)
)
3
Example 26
Project: django-treebeard Source File: admin_tree_list.py
def _subtree(context, node, request):
tree = ''
for subnode in node.get_children():
tree += format_html(
'<li>{}</li>',
mark_safe(_subtree(context, subnode, request)))
if tree:
tree = format_html('<ul>{}</ul>', mark_safe(tree))
return _line(context, node, request) + tree
3
Example 27
Project: django-rest-framework Source File: rest_framework.py
@register.simple_tag
def optional_login(request):
"""
Include a login snippet if REST framework's login view is in the URLconf.
"""
try:
login_url = reverse('rest_framework:login')
except NoReverseMatch:
return ''
snippet = "<li><a href='{href}?next={next}'>Log in</a></li>"
snippet = format_html(snippet, href=login_url, next=escape(request.path))
return mark_safe(snippet)
3
Example 28
@register.simple_tag
def pagination_link_previous(current_page, view):
if current_page.has_previous():
previous_page_number0 = current_page.previous_page_number() - 1
return format_html(
'<li class="prev"><a href="%s" class="icon icon-arrow-left">%s</a></li>' %
(view.get_query_string({PAGE_VAR: previous_page_number0}), _('Previous'))
)
return ''
3
Example 29
Project: wagtail Source File: wagtail_hooks.py
@hooks.register('insert_editor_js')
def editor_js():
return format_html(
"""
<script src="{0}"></script>
<script>
window.chooserUrls.embedsChooser = '{1}';
registerHalloPlugin('hallowagtailembeds');
</script>
""",
static('wagtailembeds/js/hallo-plugins/hallo-wagtailembeds.js'),
urlresolvers.reverse('wagtailembeds:chooser')
)
3
Example 30
Project: pycontw2016 Source File: renderers.py
def render_attached_period(begin, end):
begin = make_naive(begin.value)
end = make_naive(end.value)
return format_html(
'<div class="attached time-table__time">'
'{begin_h}:{begin_m} – {end_h}:{end_m}</div>',
begin_h=begin.hour, begin_m=begin.strftime(r'%M'),
end_h=end.hour, end_m=end.strftime(r'%M'),
)
3
Example 31
Project: pootle Source File: proxy.py
@property
def author_link(self):
return format_html(
u'<a href="{}">{}</a>',
self.get_absolute_url(),
self.display_name)
3
Example 32
def linkify(url, text=None, new_window=False):
if text is None:
text = url
target_string = ''
if new_window:
target_string = '_blank'
return format_html(
'<a href="{}" target="{}">{}</a>', url, target_string, text)
3
Example 33
def render(self):
cell__template = self.bound_column.cell.template
if cell__template:
return render_to_string(cell__template, dict(table=self.table, bound_column=self.bound_column, bound_row=self.bound_row, row=self.row, value=self.value, bound_cell=self))
else:
return format_html('<td{}>{}</td>', self.render_attrs(), self.render_cell_contents())
3
Example 34
def label_tag(self):
attrs = {}
if not self.is_first:
attrs["class"] = "inline"
label = self.field['label']
return format_html('<label{0}>{1}:</label>',
flatatt(attrs),
capfirst(force_text(label)))
3
Example 35
def add(self, data, app_label, model_name):
for index, key in enumerate(self.fields):
value = data[key]
if index == 0:
text = u'<th class="field-{0}"><a href="/admin/{1}/{2}/{3}/">{3}</a></th>'.format(
key, app_label, model_name, value
)
else:
text = u'<td class="field-{0}">{1}</td>'.format(key, value)
self.text.append(format_html(text))
3
Example 36
def render(self, name, value, attrs=None):
substitutions = {
'initial_text': self.initial_text,
'input_text': self.input_text,
}
template = '%(input)s'
substitutions['input'] = super(NotClearableFileInput, self).render(name, value, attrs)
if value:
template = self.template_with_initial
substitutions['initial'] = format_html(force_text(os.path.basename(value.name)))
return mark_safe(template % substitutions)
3
Example 37
def edit_result(self, obj):
if obj.id:
return format_html(
'<a href="/admin/iati/result/{}/" onclick="return showAddAnotherPopup(this);">Edit</a>',
str(obj.id))
else:
return format_html(
'Please save the activity to edit result details and to add indicator periods')
3
Example 38
Project: Misago Source File: djangoadmin.py
def render_edit_from_misago_link(self, *args, **kwargs):
"""
Composes an html hyperlink for the pseudo-field render.
`*args` and `**kwargs` arguments need to mimic widget `render()`
signature.
:rtype: str
"""
text = _('Edit this user in Misago admin panel')
link_html_template = ('<a href="{}" target="blank">' + text + '</a>')
link_url = reverse(
viewname='misago:admin:users:accounts:edit',
kwargs={'pk': self.instance.pk},
)
link_html = format_html(link_html_template, link_url)
return link_html
3
Example 39
Project: django-dynamic-cabinetmaps Source File: handle.py
def create(self):
rack = super(CabinetStructureFactory, self).create()
all_structure = format_html(
self.structure_template.cabinet_structure_template,
rack)
return mark_safe(all_structure)
3
Example 40
Project: SmartElect Source File: libya_bread.py
@property
def subconstituency_as_html(self):
"""Return HTML for this instance's subconstituency field that has both a human-readable
display and a link to the read view for that field (or "None")."""
if self.subconstituency is None:
return NO_LINKED_OBJECT
return format_html(ANCHOR_SNIPPET, self.subconstituency.get_absolute_url(),
self.subconstituency_name)
3
Example 41
Project: cgstudiomap Source File: admin_list.py
@register.simple_tag
def paginator_number(cl, i):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return '... '
elif i == cl.page_num:
return format_html('<span class="this-page">{}</span> ', i + 1)
else:
return format_html('<a href="{}"{}>{}</a> ',
cl.get_query_string({PAGE_VAR: i}),
mark_safe(' class="end"' if i == cl.paginator.num_pages - 1 else ''),
i + 1)
3
Example 42
Project: reviewboard Source File: builtin_fields.py
def render_value(self, user):
return format_html(
'<a class="user" href="{0}">{1}</a>',
local_site_reverse(
'user',
local_site=self.review_request_details.local_site,
args=[user]),
user.get_full_name() or user.username)
3
Example 43
@register.simple_tag(takes_context=True)
def result_tree(context, cl, request):
tree = ''
for root_node in cl.model.get_root_nodes():
tree += format_html(
'<li>{}</li>', mark_safe(_subtree(context, root_node, request)))
return format_html("<ul>{}</ul>", mark_safe(tree))
3
Example 44
Project: wagtail-cookiecutter-foundation Source File: wagtail_hooks.py
@hooks.register('insert_editor_js')
def editor_js():
# Add extra JS files to the admin
js_files = [
'js/hallo-custom.js',
]
js_includes = format_html_join(
'\n', '<script src="{0}{1}"></script>',
((settings.STATIC_URL, filename) for filename in js_files)
)
return js_includes + format_html(
"""
<script>
registerHalloPlugin('blockquotebutton');
registerHalloPlugin('blockquotebuttonwithclass');
</script>
"""
)
3
Example 45
Project: SmartElect Source File: rollgen_tags.py
@register.filter
def display_center_infos(center_infos):
"""Given a list of center info tuples, return that list as an HTML string formatted with links.
This is a specialized filter for the job view. Given a list of 2-tuples of (center id, url),
return a string of marked-safe HTML where each center id is wrapped in an <a> with href=the url.
"""
html = []
for center_id, url in center_infos:
if url:
html.append(format_html(ANCHOR_SNIPPET.format(url, center_id)))
else:
html.append(str(center_id))
delimiter = get_comma_delimiter()
return mark_safe(delimiter.join(html))
3
Example 46
Project: django-shop Source File: order.py
def print_out(self, obj):
if obj.status == 'pick_goods':
button = reverse('admin:print_confirmation', args=(obj.id,)), pgettext_lazy('admin', "Order Confirmation")
elif obj.status == 'pack_goods':
button = reverse('admin:print_invoice', args=(obj.id,)), pgettext_lazy('admin', "Invoice")
else:
button = None
if button:
return format_html(
'<span class="object-tools"><a href="{0}" class="viewsitelink" target="_new">{1}</a></span>',
*button)
return ''
3
Example 47
Project: taiga-back Source File: admin.py
def owner_url(self, obj):
if obj.owner:
url = reverse('admin:{0}_{1}_change'.format(obj.owner._meta.app_label,
obj.owner._meta.model_name),
args=(obj.owner.pk,))
return format_html("<a href='{url}' title='{user}'>{user}</a>", url=url, user=obj.owner)
return ""
3
Example 48
def render_block(
event, time_map, events, extra_classes=None, *,
min_height=0, max_height=None):
location = event.location
height = time_map[event.end_time] - time_map[event.begin_time]
if max_height is not None:
height = min(height, max_height)
if height == 1 and min_height < 1 and not _has_tall_event(events):
height = 'small'
return format_html(
'<div class="slot-item slot-item--w{w} slot-item--h{h}{classes}">'
'{location}{event}</div>',
w=Location.get_md_width(location),
h=height,
location=render_block_location(location),
event=render_event(event),
classes=(' ' + ' '.join(extra_classes) if extra_classes else ''),
)
3
Example 49
Project: reviewboard Source File: reviewtags.py
@register.simple_tag(takes_context=True)
def expand_fragment_header_link(context, header):
"""Render a diff comment fragment header expansion link.
This link expands the context to contain the given line number.
"""
lines_of_context = context['lines_of_context']
offset = context['first_line'] - header['line']
return render_to_string('reviews/expand_link.html', {
'tooltip': _('Expand to header'),
'text': format_html('<code>{0}</code>', header['text']),
'comment_id': context['comment'].id,
'expand_pos': (lines_of_context[0] + offset,
lines_of_context[1]),
'image_class': 'rb-icon-diff-expand-header',
})
3
Example 50
def render(self):
"""
Outputs a <div> for this set of choice fields.
If an id was given to the field, it is applied to the <di> (each
item in the list will get an id of `$id_$i`).
"""
id_ = self.attrs.get('id', None)
start_tag = format_html('<div id="{0}">', id_) if id_ else '<div>'
output = [start_tag]
for widget in self:
output.append(format_html('<div class="radio">{0}</div>', force_text(widget)))
output.append('</div>')
return mark_safe('\n'.join(output))