Here are the examples of the python api django_jinja.library.global_function taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
126 Examples
4
Example 1
Project: taiga-back Source File: functions.py
@library.global_function
def lists_diff(list1, list2):
"""
Get the difference of two list and remove None values.
>>> list1 = ["a", None, "b", "c"]
>>> list2 = [None, "b", "d", "e"]
>>> list(filter(None.__ne__, set(list1) - set(list2)))
['c', 'a']
"""
return list(filter(None.__ne__, set(list1) - set(list2)))
3
Example 2
@library.global_function
def almost_equal(date1, date2):
"""return true if the only difference between these two dates are
their microseconds."""
diff = abs(date1 - date2)
return not diff.seconds and not diff.days
3
Example 3
@library.global_function
def profile_url(user, edit=False):
"""Return a URL to the user's profile."""
if edit:
return reverse('users.edit_profile', args=[user.username])
return reverse('users.profile', args=[user.username])
3
Example 4
@library.global_function
@contextfunction
def providers_media_js(context):
"""
{{ providers_media_js() }}
"""
request = context['request']
return Markup(u'\n'.join([p.media_js(request)
for p in providers.registry.get_list()]))
3
Example 5
@jinja2.contextfunction
@library.global_function
def number(context, n):
"""Return the localized representation of an integer or decimal.
For None, print nothing.
"""
if n is None:
return ''
return format_decimal(n, locale=_babel_locale(_contextual_locale(context)))
3
Example 6
Project: airmozilla Source File: jinja_helpers.py
@library.global_function
def render_transcript(transcript):
html = []
template = engines['backend'].from_string(
'<p data-start="{{ start }}" data-end="{{ end }}">{{ text }}</p>'
)
for segment in transcript['subtitles']:
context = {
'start': segment['start'],
'end': segment['end'],
'text': segment['text'].replace('<br>', ' '),
}
html.append(template.render(context))
return mark_safe('\n'.join(html))
3
Example 7
@library.global_function
@jinja2.contextfunction
def datetimeformat(context, value, format='shortdatetime', output='html'):
"""
Returns date/time formatted using babel's locale settings. Uses the
timezone from settings.py
"""
request = context['request']
formatted, tzvalue = format_date_time(request, value, format)
if output == 'json':
return formatted
return jinja2.Markup('<time datetime="%s">%s</time>' %
(tzvalue.isoformat(), formatted))
3
Example 8
Project: airmozilla Source File: jinja_helpers.py
@library.global_function
@jinja2.contextfunction
def abs_static(context, path):
"""Make sure we always return a FULL absolute URL that starts
with 'http'.
"""
return get_abs_static(path, context['request'])
3
Example 9
Project: airmozilla Source File: jinja_helpers.py
@library.global_function
def recurse_comments(comment, discussion,
request, query_filter, can_manage_comments):
comments = Comment.objects.filter(reply_to=comment)
comments = comments.filter(query_filter)
context = {
'comments': comments.order_by('created'),
'discussion': discussion,
'request': request,
'Comment': Comment,
'can_manage_comments': can_manage_comments,
'root': False,
'query_filter': query_filter,
}
return jinja2.Markup(
render_to_string('comments/comments.html', context)
)
3
Example 10
Project: kuma Source File: jinja_helpers.py
@library.global_function
def colorize_diff(diff):
# we're doing something horrible here because this will show up
# in feed reader and other clients that don't load CSS files
diff = diff.replace('<span class="diff_add"', '<span class="diff_add" '
'style="background-color: #afa; text-decoration: none;"')
diff = diff.replace('<span class="diff_sub"', '<span class="diff_sub" '
'style="background-color: #faa; text-decoration: none;"')
diff = diff.replace('<span class="diff_chg"', '<span class="diff_chg" '
'style="background-color: #fe0; text-decoration: none;"')
return diff
3
Example 11
Project: airmozilla Source File: jinja_helpers.py
@library.global_function
def star_tag(id, extra_classes=None):
extra_classes = extra_classes or []
if isinstance(extra_classes, basestring):
extra_classes = [extra_classes]
extra_classes.insert(0, 'star')
html = (
'<a class="{0}" data-id="{1}" '
'data-star-on="Remove star" data-star-off="Save as a starred event"'
'></a>'.format(
' '.join(extra_classes),
id
)
)
return mark_safe(html)
3
Example 12
@library.global_function
def url(viewname, *args, **kwargs):
"""Helper for Django's ``reverse`` in templates.
Uses sumo's locale-aware reverse."""
locale = kwargs.pop('locale', None)
return reverse(viewname, locale=locale, args=args, kwargs=kwargs)
3
Example 13
@library.global_function
def thousands(number):
"""AKA ``thousands separator'' - 1000000 becomes 1,000,000 """
try:
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
except locale.Error:
locale.setlocale(locale.LC_ALL, '')
return locale.format('%d', number, True)
3
Example 14
@library.global_function
def static(path):
"""Generate a URL for the specified static file."""
try:
return django_static(path)
except ValueError as err:
log.error('Static helper error: %s' % err)
return ''
3
Example 15
Project: browsercompat Source File: helpers.py
@library.global_function
@contextfunction
def pick_translation(context, trans_obj):
"""Pick a translation from a translation object.
A translation object may be:
Empty -- No content, return ('', None)
A string -- A canonical string, return (string, None)
A dictionary -- Language/string pairs, return (string, language)
"""
if not trans_obj:
return '', None
if not hasattr(trans_obj, 'keys'):
return trans_obj, None
lang = context.get('lang', 'en')
if lang not in trans_obj:
assert 'en' in trans_obj
lang = 'en'
return trans_obj[lang], lang
3
Example 16
@library.global_function
def user_list(users):
"""Turn a list of users into a list of links to their profiles."""
link = u'<a class="user" href="%s">%s</a>'
list = u', '.join([link % (escape(profile_url(u)), escape(u.username)) for
u in users])
return Markup(list)
3
Example 17
Project: airmozilla Source File: jinja_helpers.py
@library.global_function
def clashes_with_event(url):
"""used for URLs belonging to Flatpages to see if their
URL is possibly clashing with an event.
"""
possible = url.split('/', 2)[1]
try:
return Event.objects.get(slug=possible)
except Event.DoesNotExist:
try:
return EventOldSlug.objects.get(slug=possible).event
except EventOldSlug.DoesNotExist:
return False
3
Example 18
Project: kuma Source File: jinja_helpers.py
@library.global_function
def admin_link(user):
"""Returns a link to admin a user"""
url = reverse('admin:users_user_change', args=(user.id,),
current_app=admin.site.name)
link = ('<a href="%s" class="button neutral">%s'
'<i aria-hidden="true" class="icon-wrench"></i></a>' %
(url, ugettext('Admin')))
return Markup(link)
3
Example 19
@library.global_function
def user_list(users):
"""Turn a list of users into a list of links to their profiles."""
link = u'<a href="%s">%s</a>'
list = u', '.join([link % (escape(u.get_absolute_url()), escape(u.username)) for
u in users])
return Markup(list)
3
Example 20
Project: kuma Source File: jinja_helpers.py
@library.global_function
def tag_diff_table(prev_tags, curr_tags, prev_id, curr_id):
html_diff = difflib.HtmlDiff(wrapcolumn=DIFF_WRAP_COLUMN)
diff = html_diff.make_table([prev_tags], [curr_tags],
ugettext('Revision %s') % prev_id,
ugettext('Revision %s') % curr_id)
# Simple formatting update: 784877
diff = diff.replace('",', '"<br />').replace('<td', '<td valign="top"')
return jinja2.Markup(diff)
3
Example 21
Project: airmozilla Source File: jinja_helpers.py
@library.global_function
def event_status_to_css_label(status):
if status in (Event.STATUS_INITIATED, Event.STATUS_SUBMITTED):
return 'label-default'
if status in (Event.STATUS_PENDING, Event.STATUS_PROCESSING):
return 'label-primary'
if status == Event.STATUS_SCHEDULED:
return 'label-success'
if status == Event.STATUS_REMOVED:
return 'label-danger'
raise NotImplementedError(status)
3
Example 22
Project: airmozilla Source File: jinja_helpers.py
@library.global_function
def highlight_stopwords(text, class_='stopword', not_class='not-stopword'):
words = []
for word in text.split():
if word.lower() in STOPWORDS or word in '-?':
css_class = class_
else:
css_class = not_class
words.append('<span class="%s">%s</span>' % (
css_class,
jinja2.escape(word)
))
return jinja2.Markup(' '.join(words))
3
Example 23
@library.global_function
@contextfunction
def providers_media_js(context):
"""Get a list of socialaccount providers.
Jingo version of providers_media_js from
allauth/socialaccount/templatetags/socialaccount.py
"""
request = context['request']
ret = '\n'.join(
[p.media_js(request) for p in providers.registry.get_list()])
return ret
3
Example 24
Project: airmozilla Source File: jinja_helpers.py
@library.global_function
def gravatar_src(email, secure, size=None):
if secure:
tmpl = '//secure.gravatar.com/avatar/%s'
else:
tmpl = '//www.gravatar.com/avatar/%s'
url = tmpl % hashlib.md5(email.lower()).hexdigest()
url += '?d=identicon'
if size is not None:
url += '&s=%s' % size
return url
3
Example 25
Project: airmozilla Source File: jinja_helpers.py
@library.global_function
def truncate_url(url, max_length=20, ellipsis=u'\u2026'):
if len(url) < max_length:
return url
left, right = '', ''
i = 0
while len(left) + len(right) < max_length:
i += 1
left = url[:i]
right = url[-i:]
return u'%s%s%s' % (left, ellipsis, right)
3
Example 26
Project: kitsune Source File: jinja_helpers.py
@jinja2.contextfunction
@library.global_function
def has_perm_or_owns(context, perm, obj, perm_obj, field_name='creator'):
"""
Check if the user has a permission or owns the object.
Ownership is determined by comparing perm_obj.field_name to the user in
context.
"""
user = context['request'].user
if user.is_anonymous():
return False
return access.has_perm_or_owns(user, perm, obj, perm_obj, field_name)
3
Example 27
Project: kitsune Source File: jinja_helpers.py
@library.global_function
def karma_titles(user):
"""Return a list of titles for a given user."""
# Titles assigned to the user or groups
return Title.objects.filter(
Q(users=user) | Q(groups__in=user.groups.all())).distinct()
3
Example 28
@library.global_function
def truncate_chars(text, chars, ellipsis=u'…', left=False):
assert chars > 4, chars
if len(text) > chars:
if left:
text = '%s%s' % (
ellipsis,
text[len(text) - chars:].strip(),
)
else:
text = '%s%s' % (
text[:chars - 1].strip(),
ellipsis
)
return text
3
Example 29
Project: kitsune Source File: jinja_helpers.py
@library.global_function
def unlocalized_url(viewname, *args, **kwargs):
"""Helper for Django's ``reverse`` in templates.
Uses django's default reverse."""
return django_reverse(viewname, args=args, kwargs=kwargs)
3
Example 30
Project: browsercompat Source File: helpers.py
@library.global_function
@contextfunction
def drop_filter_from_current_url(context, name):
"""Drop a filter from the current URL."""
query_parts = []
for qs_name, qs_value in context['request'].GET.items():
if qs_name != name:
query_parts.append((qs_name, qs_value))
path = context['request'].path
if query_parts:
return path + '?' + urlencode(query_parts)
else:
return path
3
Example 31
@jinja2.contextfunction
@library.global_function
def is_secure(context):
request = context.get('request')
if request and hasattr(request, 'is_secure'):
return context.get('request').is_secure()
return False
3
Example 32
Project: airmozilla Source File: jinja_helpers.py
@library.global_function
@jinja2.contextfunction
def make_absolute(context, uri):
if '://' not in uri:
request = context['request']
prefix = request.is_secure() and 'https' or 'http'
if uri.startswith('//'):
# we only need the prefix
uri = '%s:%s' % (prefix, uri)
else:
uri = '%s://%s%s' % (prefix, RequestSite(request).domain, uri)
return uri
3
Example 33
Project: kitsune Source File: jinja_helpers.py
@library.global_function
def get_profile(user):
try:
return Profile.objects.get(user_id=user.id)
except Profile.DoesNotExist:
return None
3
Example 34
@library.global_function
def verbose_name(obj_class, field_name):
if field_name in EXTRA_FIELD_VERBOSE_NAMES:
return EXTRA_FIELD_VERBOSE_NAMES[field_name]
try:
return obj_class._meta.get_field(field_name).verbose_name
except Exception:
return field_name
3
Example 35
Project: kitsune Source File: jinja_helpers.py
@library.global_function
def display_name(user):
"""Return a display name if set, else the username."""
try: # Also mostly for tests.
profile = Profile.objects.get(user_id=user.id)
except (Profile.DoesNotExist, AttributeError):
return user.username
return profile.display_name if profile else user.username
3
Example 36
@library.global_function
def query_string(request, **kwargs):
current = request.META.get('QUERY_STRING')
parsed = cgi.parse_qs(current)
parsed.update(kwargs)
return urllib.urlencode(parsed, True)
3
Example 37
Project: kitsune Source File: jinja_helpers.py
@library.global_function
def private_message(user):
"""Return a link to private message the user."""
url = urlparams(reverse('messages.new'), to=user.username)
msg = _('Private message')
return Markup(u'<p class="pm"><a href="{url}">{msg}</a></p>'.format(
url=url, msg=msg))
3
Example 38
Project: browsercompat Source File: helpers.py
@library.global_function
@contextfunction
def trans_str(context, trans_obj):
"""Pick a translation as an unescaped string.
The string is not wrapped in an HTML element and not marked as HTML safe.
"""
return pick_translation(context, trans_obj)[0]
3
Example 39
Project: kuma Source File: jinja_helpers.py
@library.global_function
def gravatar_url(email, secure=True, size=220, rating='pg',
default=settings.DEFAULT_AVATAR):
job = UserGravatarURLJob()
return job.get(email, secure=secure, size=size,
rating=rating, default=default)
3
Example 40
@library.global_function
def format_message(message):
if hasattr(message, 'message'):
# it's a django.contrib.messages.base.Message instance
message = message.message
if basic_markdown_link.findall(message):
whole, label, link = basic_markdown_link.findall(message)[0]
message = message.replace(
whole,
'<a href="%s" class="message-inline">%s</a>'
% (link, label)
)
message = jinja2.Markup(message)
return message
3
Example 41
@library.global_function
def get_language_choices():
"""
Get language choices as code and text in two languages.
:return:
Available language codes as tuples (code, name, local_name)
where name is in the currently active language, and local_name
is in the language of the item.
:rtype: Iterable[tuple[str,str,str]]
"""
for (code, name) in settings.LANGUAGES:
lang_info = translation.get_language_info(code)
name_in_current_lang = translation.ugettext(name)
local_name = lang_info["name_local"]
yield (code, name_in_current_lang, local_name)
3
Example 42
Project: kitsune Source File: jinja_helpers.py
@library.global_function
def group_avatar(group_profile):
"""Return a URL to the group's avatar."""
if group_profile.avatar:
return group_profile.avatar.url
else:
return settings.STATIC_URL + settings.DEFAULT_AVATAR
3
Example 43
Project: kuma Source File: jinja_helpers.py
@library.global_function
def social_accounts(user):
"""
{% set accounts = social_accounts(user) %}
Then:
{{ accounts.twitter }} -- a list of connected Twitter accounts
{{ accounts.twitter.0 }} -- the first Twitter account
{% if accounts %} -- if there is at least one social account
"""
accounts = {}
if not user.is_authenticated():
return accounts
for account in user.socialaccount_set.all().iterator():
providers = accounts.setdefault(account.provider, [])
providers.append(account)
return accounts
3
Example 44
Project: airmozilla Source File: jinja_helpers.py
@library.global_function
def comment_status_to_css_label(status):
# because this just got too messy in the template
if status == Comment.STATUS_APPROVED:
return 'label-success'
elif status == Comment.STATUS_REMOVED:
return 'label-danger'
return 'label-info'
3
Example 45
Project: airmozilla Source File: jinja_helpers.py
@library.global_function
def show_duration_compact(duration):
hours = duration / 3600
seconds = duration % 3600
minutes = seconds / 60
seconds = seconds % 60
out = []
if hours:
out.append('%dh' % hours)
if hours or minutes:
out.append('%dm' % minutes)
if hours or minutes or seconds:
out.append('%ds' % seconds)
return ''.join(out)
3
Example 46
Project: shuup Source File: prices.py
@django_jinja.library.global_function
@jinja2.contextfunction
def show_prices(context):
"""
Return true if price display options has show prices enabled.
:type context: jinja2.runtime.Context
"""
options = PriceDisplayOptions.from_context(context)
return options.show_prices
3
Example 47
@library.global_function(name="resolve_front_url")
def resolve(type, *args):
site = get_site_by_id("front")
url_tmpl = "{scheme}//{domain}{url}"
scheme = site.scheme and "{0}:".format(site.scheme) or ""
url = urls[type].format(*args)
return url_tmpl.format(scheme=scheme, domain=site.domain, url=url)
3
Example 48
Project: browsercompat Source File: helpers.py
@library.global_function
@contextfunction
def add_filter_to_current_url(context, name, value):
"""Add a filter to the current URL."""
query_parts = []
added = False
for qs_name, qs_value in context['request'].GET.items():
if qs_name == name:
added = True
query_parts.append((name, value))
else:
query_parts.append((qs_name, qs_value))
if not added:
query_parts.append((name, value))
return context['request'].path + '?' + urlencode(query_parts)
3
Example 49
Project: airmozilla Source File: jinja_helpers.py
@library.global_function
def short_desc(event, words=25, strip_html=False):
"""Takes an event object and returns a shortened description."""
if event.short_description:
description = event.short_description
else:
description = event.description
if strip_html:
description = unhtml(description)
return Truncator(description).words(words)
3
Example 50
Project: kitsune Source File: jinja_helpers.py
@library.global_function
def group_link(group):
try:
profile = GroupProfile.objects.get(group=group)
url = reverse('groups.profile', args=[profile.slug])
html = '<a href="%s">%s</a>' % (jinja2.escape(url), jinja2.escape(group.name))
return jinja2.Markup(html)
except GroupProfile.DoesNotExist:
return group.name