class SimpleTagRegistrationTests(TestCase): def setUp(self): self.library = Library() def test_simple_tag(self): @self.library.simple_tag def func(): return '' self.assertIn('func', self.library.tags) def test_simple_tag_parens(self): @self.library.simple_tag() def func(): return '' self.assertIn('func', self.library.tags) def test_simple_tag_name_kwarg(self): @self.library.simple_tag(name='name') def func(): return '' self.assertIn('name', self.library.tags) def test_simple_tag_invalid(self): msg = "Invalid arguments provided to simple_tag" with self.assertRaisesMessage(ValueError, msg): self.library.simple_tag('invalid')
class SimpleTagRegistrationTests(TestCase): def setUp(self): self.library = Library() def test_simple_tag(self): @self.library.simple_tag def func(): return '' self.assertIn('func', self.library.tags) def test_simple_tag_parens(self): @self.library.simple_tag() def func(): return '' self.assertIn('func', self.library.tags) def test_simple_tag_name_kwarg(self): @self.library.simple_tag(name='name') def func(): return '' self.assertIn('name', self.library.tags) def test_simple_tag_invalid(self): msg = "Invalid arguments provided to simple_tag" with self.assertRaisesMessage(ValueError, msg): self.library.simple_tag('invalid')
class SimpleTagRegistrationTests(SimpleTestCase): def setUp(self): self.library = Library() def test_simple_tag(self): @self.library.simple_tag def func(): return '' self.assertIn('func', self.library.tags) def test_simple_tag_parens(self): @self.library.simple_tag() def func(): return '' self.assertIn('func', self.library.tags) def test_simple_tag_name_kwarg(self): @self.library.simple_tag(name='name') def func(): return '' self.assertIn('name', self.library.tags) def test_simple_tag_invalid(self): msg = "Invalid arguments provided to simple_tag" with self.assertRaisesMessage(ValueError, msg): self.library.simple_tag('invalid') def test_simple_tag_wrapped(self): @self.library.simple_tag @functools.lru_cache(maxsize=32) def func(): return '' func_wrapped = self.library.tags['func'].__wrapped__ self.assertIs(func_wrapped, func) self.assertTrue(hasattr(func_wrapped, 'cache_info'))
from django.template import Library, Node, TemplateSyntaxError from django.template import Variable, resolve_variable from django.utils.translation import ugettext as _ from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse register = Library() def disconnect_url(provider): return "" register.simple_tag(disconnect_url)
from django.template import Library register = Library() def mobileadmin_media_prefix(): """ Returns the string contained in the setting MOBILEADMIN_MEDIA_PREFIX. """ try: from mobileadmin.conf import settings except ImportError: return '' return settings.MEDIA_PREFIX mobileadmin_media_prefix = register.simple_tag(mobileadmin_media_prefix)
""" get the theme name from settings.py """ theme_name = theme() if theme_name: return theme_name else: return 'default' def media_url(): """ Returns the common media url """ return getattr(settings,'MEDIA_URL','') media_url = register.simple_tag(media_url) def theme_media_url(): """ Returns the themes media url """ return media_url() + '/themes/'+ get_theme_name() register.simple_tag(theme_media_url) def theme_template_url(): """ Returns the themes template url """ url = 'themes/'+ get_theme_name()
# -*- coding: utf-8 -*- from django.conf import settings from django.template import Library from django.contrib.auth.models import * from abe.missions.settings import * register = Library() def render_mission_notification(): return MISSION_NOTIFICATION_TOKEN register.simple_tag( render_mission_notification )
from django.template import Library register = Library() def app_static_prefix(): """ Returns the string contained in the setting settings.STATIC_URL. """ try: from django.conf import settings except ImportError: return '' return settings.STATIC_PREFIX app_static_prefix = register.simple_tag(app_static_prefix)
from __future__ import absolute_import from django.conf import settings from django.template import Library from sentry import options from sentry.utils.assets import get_asset_url from sentry.utils.http import absolute_uri register = Library() register.simple_tag(get_asset_url, name='asset_url') @register.simple_tag def absolute_asset_url(module, path): """ Returns a versioned absolute asset URL (located within Sentry's static files). Example: {% absolute_asset_url 'sentry' 'dist/sentry.css' %} => "http://sentry.example.com/_static/74d127b78dc7daf2c51f/sentry/dist/sentry.css" """ return absolute_uri(get_asset_url(module, path)) @register.simple_tag def crossorigin(): """ Returns an additional crossorigin="anonymous" snippet for use in a <script> tag if our asset urls are from a different domain than the system.url-prefix.
from django.template import Library register = Library() def media_prefix(): """ Returns the string contained in the setting MEDIA_URL. """ try: from django.conf import settings except ImportError: return '' return settings.MEDIA_URL media_prefix = register.simple_tag(media_prefix)
pages = FlatPage.objects.all().order_by('url') from django.utils.datastructures import SortedDict tree = SortedDict() for page in pages: segs = page.url.split('/')[2:-1] # removes /wiki/ and empty last string if len(segs) > 0: tree[page.url] = [page, {}] menu = '<p><a href="/">Home</a></p>' for p in tree.keys(): menu += _add_page(tree[p][0]) #menu += '<li><a href="%s" title="%s">%s</a></li>' % (tree[p][0].url, tree[p][0].title, tree[p][0].url) #menu += '</ul>' return menu register.simple_tag(flatpage_tree) def flatpage_menu(): # Create an unordered list of all flatpages pages = FlatPage.objects.all() menu = '<ul>' for i in range(len(pages)): menu += '<li>'+'<a href="'+pages[i].url+'" title="'+pages[i].title+'">'+pages[i].title+'</a></li>' menu += '</ul>' return menu register.simple_tag(flatpage_menu) import calendar @register.filter def weekdayabbr(value):
#!/usr/bin/env python #coding=utf-8 from django.template import Library from django.conf import settings from utils.version import get_svn_revision register = Library() VERSION = getattr(settings, 'VERSION', 'unknown') def get_version(): """ Returns the version as a human-format string. """ v = '.'.join([str(i) for i in VERSION[:-1]]) if VERSION[-1]: v = '%s%s %s' % (v, VERSION[-1], get_svn_revision()) return v register.simple_tag(get_version)
if not user: return '' notifications = user.notifications.unread() company = context['request'].company if company: notifications = notifications.filter( target_object_id=company.id, target_content_type=ContentType.objects.get_for_model(company), ) return notifications.count() if StrictVersion(get_version()) >= StrictVersion('2.0'): notifications_unread = register.simple_tag(takes_context=True)( notifications_unread) # pylint: disable=invalid-name else: notifications_unread = register.assignment_tag(takes_context=True)( notifications_unread) # noqa # Requires vanilla-js framework - http://vanilla-js.com/ @register.simple_tag def register_notify_callbacks( badge_class='live_notify_badge', # pylint: disable=too-many-arguments,missing-docstring menu_class='live_notify_list', refresh_period=15, callbacks='', api_name='list', fetch=5): refresh_period = int(refresh_period) * 1000
from django.template import Library, Node, resolve_variable from django.utils.html import escape register = Library() def greeting(name): return 'Hello, %s!' % escape(name) greeting = register.simple_tag(greeting)
media url (or other location if an absolute url is given). Example usage:: {% include_admin_script "calendar.js" %} could return:: <script type="text/javascript" src="/media/calendar.js"> """ if not absolute_url_re.match(script_path): script_path = '%s%s' % (settings.ADMIN_MEDIA_PREFIX, script_path) return '<script type="text/javascript" src="%s"></script>' % script_path include_admin_script = register.simple_tag(include_admin_script) def submit_row(context): change = context['change'] is_popup = context['is_popup'] return { 'onclick_attrib': '', 'show_delete_link': False, #should just set status to mark delete only. can delete permanently by appengine dataview 'show_save_as_new': not is_popup and change, 'show_save_and_add_another': not is_popup and not change, 'show_save': True }
if count: output = '<span id="ow-notification-count">{0}</span>' output = format_html(output.format(count)) return output def notification_widget(): return format_html(''' <div class="ow-notification-dropdown ow-hide"> <div class="filters"> <span class="btn" id="ow-mark-all-read" tabindex="0" role="button">Mark all as read</span> <span class="btn" id="ow-show-unread" tabindex="0" role="button">Show unread only</span> </div> <div class="ow-notification-wrapper ow-round-bottom-border"> <div id="ow-notifications-loader" class="ow-hide"><div class="loader"></div></div> </div> <div class="ow-no-notifications ow-round-bottom-border ow-hide"> <p>No new notification.</p> </div> </div> ''') def notification_toast(): return format_html('<div class="ow-notification-toast-wrapper"></div>') register.simple_tag(takes_context=True)(unread_notifications) register.simple_tag(takes_context=False)(notification_widget) register.simple_tag(takes_context=False)(notification_toast)
from django.template import Library from django.utils.encoding import iri_to_uri from django.core.urlresolvers import reverse register = Library() def cropduster_media_prefix(): """ Returns the string contained in the setting ADMIN_MEDIA_PREFIX. """ media_url = reverse('cropduster-static', kwargs={'path': ''}) return iri_to_uri(media_url) cropduster_media_prefix = register.simple_tag(cropduster_media_prefix)
def is_image(file): """ Check if the file is a image based on the extension """ img_exts = [".jpeg", ".png", ".gif", ".jpg", ".bmp"] for ext in img_exts: if file.url.lower().find(ext) != -1: return True return False def display_file(value): """ If file is an image display <img> tag with the file as src, otherwise display <a> link with file as href """ if value in (None, ''): return "" if is_image(value): return u'<a href="%s%s" title="click to view full size image" class="thumb"><img width="100" src="%s%s"/></a><br/>' % ( settings.MEDIA_URL, value, settings.MEDIA_URL, value) return u'<a href="%s%s"><span class="glyphicon glyphicon-picture">' % ( settings.MEDIA_URL, value, ) display_file = register.simple_tag(display_file)
path = settings.MEDIA_ROOT if (fname != ''): path = path+'/'+str(fname) downloadpath = downloadpath+str(fname) if (os.path.isfile(path)): return "href='"+downloadpath+"'" return " href=# onclick=javascript:alert('File-doesnot-exists');" def truncchar(value, arg): if len(value) < arg: return value else: return value[:arg] + '...' register.simple_tag(tags) register.simple_tag(tagvalid) register.simple_tag(tagtaskliststatus) register.simple_tag(tagnonprojecttaskstatus) register.simple_tag(tagstatus) register.simple_tag(seltaskname) register.simple_tag(seltaskid) register.simple_tag(validdate) register.simple_tag(validdateactual) register.simple_tag(artifactreadonly) register.simple_tag(fileexists) register.filter(truncchar)
from notifications.templatetags.notifications_tags import notifications_unread Notification = swapper.load_model('notifications', 'Notification') register = Library() def get_notifications_count(context): user_pk = context['user'].is_authenticated and context['user'].pk cache_key = Notification.COUNT_CACHE_KEY.format(user_pk) count = cache.get(cache_key) if count is None: count = notifications_unread(context) cache.set(cache_key, count) return count def unread_notifications(context): count = get_notifications_count(context) output = '' if count: output = '<span>{0}</span>' output = format_html(output.format(count)) return output if StrictVersion(get_version()) >= StrictVersion('2.0'): register.simple_tag(takes_context=True)(unread_notifications) else: register.assignment_tag(takes_context=True)(notifications_unread)
from django.template import Library from django.conf import settings register = Library() def media_url(): """ Returns the string contained in the setting MEDIA_URL. """ return settings.MEDIA_URL media_url = register.simple_tag(media_url) def static_url(): """ Returns the string contained in the setting MEDIA_URL. """ return settings.STATIC_URL media_url = register.simple_tag(static_url) def passed_icon(is_passed=True): if is_passed: img_src = "/image/Clear.png" else: img_src = "/image/MinusRed.png"
from django.template import Library register = Library() def app_static_prefix(): """ Returns the string contained in the setting settings.STATIC_URL. """ try: from django.conf import settings except ImportError: return '' return settings.STATIC_PREFIX app_static_prefix = register.simple_tag(app_static_prefix)
""" Renders an activity stream as a list into the template's context. Streams loaded by stream_type can be the default ones (eg user, actor, etc.) or a user defined stream. Extra args/kwargs are passed into the stream call. :: {% activity_stream 'actor' user %} {% for action in stream %} {% display_action action %} {% endfor %} """ if stream_type == 'model': stream_type = 'model_actions' if not hasattr(Action.objects, stream_type): raise TemplateSyntaxError('Action manager has no attribute: %s' % stream_type) ctxvar = kwargs.pop('as', 'stream') context[ctxvar] = getattr(Action.objects, stream_type)(*args, **kwargs) return '' register.filter(activity_stream) register.filter(is_following) register.tag('is_following', is_following_tag) register.tag(display_action) register.tag(follow_url) register.tag(follow_all_url) register.tag(actor_url) register.simple_tag(takes_context=True)(activity_stream)
register = Library() def media(path): """ Returns the string contained in the setting ADMIN_MEDIA_PREFIX. """ try: from django.conf import settings except ImportError: return path # p = getattr(settings, 'VERSION', '1') return settings.MEDIA_URL + path # + "?v=" + p register.simple_tag(media) def style(path): return '<link rel="stylesheet" type="text/css" href="%s"/>' % media(path) register.simple_tag(style) def jscript(path): return '<script type="text/javascript" src="%s"></script>' % media(path) register.simple_tag(jscript)
from django.template import Library from django.utils.encoding import iri_to_uri register = Library() def manager_media_prefix(): try: from django.conf import settings except ImportError: return '' return iri_to_uri(settings.MANAGER_MEDIA_PREFIX) manager_media_prefix = register.simple_tag(manager_media_prefix)
from django.template import Library register = Library() def media_url(): try: from django.conf import settings except ImportError: return '' return settings.MEDIA_URL media_url = register.simple_tag(media_url)
from django.utils.encoding import force_unicode from django.utils.safestring import mark_safe register = Library() def fields_values(d, k): """ >>> data = {'name1': ['value1.1', 'value1.2'], 'name2': ['value2.1', 'value2.2'], } >>> field_values(data, 'name1') value1.1, value1.2 """ values = d.get(k, []) return ",".join(map(str, values)) fields_values = register.simple_tag(fields_values) def link_fields_values(d, k): """ >>> data = {'name1': ['value1.1', 'value1.2'], 'name2': ['value2.1', 'value2.2'], } >>> link_fields_values(data, 'name1') u'<a href="#" class="fastfieldvalue name1">value1.1</a>, <a href="#" class="fastfieldvalue name1">value1.2</a>' """ ret = [] for v in d.get(k, []): if v == '': # ignore empty continue ret.append('<a href="#" class="fastfieldvalue %s value">%s</a>' % (k, force_unicode(v))) return mark_safe(", ".join(ret))
from reinhardt.templatetags.expr import do_expr from reinhardt.templatetags.lookup import lookup from reinhardt.templatetags.var import do_variables from syr.times import timedelta_to_human_readable from syr.utils import get_absolute_url from syr.log import get_log log = get_log() register = Library() static_url_prefix = get_absolute_url(settings.STATIC_URL, settings.CONTENT_HOME_URL) # register imported tags and filters that we want to include when we load 'custom' # re-registering django.templatetags.static.static apparently works register.simple_tag(django.templatetags.static.static) register.filter('data_img', data_img) register.filter('lookup', lookup) register.tag('var', do_variables) def get_title(title): # this is a special case title = settings.TOP_LEVEL_DOMAIN.title() if title == 'Goodcrypto': title = 'GoodCrypto' if settings.CONTENT_HOME_URL == 'http://127.0.0.1': title += ' Server' return title register.simple_tag(get_title) def debugging():
from django.template import Library import urllib, hashlib register = Library() SIZE = 64 def gravatar(context): email = context['user'].email gravatar_url = 'http://www.gravatar.com/avatar/' + hashlib.md5( email.lower()).hexdigest() + '?' gravatar_url += urllib.urlencode({'d': 'identicon', 's': str(SIZE)}) return ('<a class="gravatar" href="http://en.gravatar.com/">' '<img src="%s">' '<div class="image_overlay">Change Picture</div>' '</a>') % gravatar_url register.simple_tag(gravatar, takes_context=True)
from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse # pylint: disable=no-name-in-module,import-error register = Library() def notifications_unread_fn(context, recipient=None): recip = recipient or user_context(context) return Notification.objects.filter( recipient_content_type_id=ContentType.objects.get_for_model(recip).id, recipient_object_id=recip.id).unread().count() if StrictVersion(get_version()) >= StrictVersion('2.0'): register.simple_tag(name='notifications_unread', takes_context=True)(notifications_unread_fn) # pylint: disable=invalid-name else: register.assignment_tag(name='notifications_unread', takes_context=True)(notifications_unread_fn) # pylint: disable=invalid-name @register.filter def has_notification(user): recip = user if recip: return Notification.objects.filter( recipient_content_type_id=ContentType.objects.get_for_model(recip).id, recipient_object_id=recip.id).unread().exists() return False # Requires vanilla-js framework - http://vanilla-js.com/
from django.template import Library register = Library() def times_ranked(player, rank=0, num_players=0): if rank > num_players and num_players != 0: return "-" return str(player.times_ranked(rank, num_players)) def high_score(player, num_players=0): return str(player.high_score(num_players)) def low_score(player, num_players=0): return str(player.low_score(num_players)) register.simple_tag(times_ranked) register.simple_tag(high_score) register.simple_tag(low_score)
""" jsprefix.py. Registers A new tag for use in templates. Define JS_PREFIX in the top-level settings.py file and you can use {% load customtags %} and then {% js_prefix %} in templates. Allows for relocation of content. """ from django.template import Library register = Library() def js_prefix(): """ Returns the string contained in the setting JS_PREFIX """ try: from django.conf import settings except ImportError: return '' return settings.JS_PREFIX js_prefix = register.simple_tag(js_prefix)
pages = FlatPage.objects.all().order_by('url') from django.utils.datastructures import SortedDict tree = SortedDict() for page in pages: segs = page.url.split('/')[2:-1] # removes /wiki/ and empty last string if len(segs) > 0: tree[page.url] = [page, {}] menu = '<p><a href="/">Home</a></p>' for p in tree.keys(): menu += _add_page(tree[p][0]) #menu += '<li><a href="%s" title="%s">%s</a></li>' % (tree[p][0].url, tree[p][0].title, tree[p][0].url) #menu += '</ul>' return menu register.simple_tag(flatpage_tree) def flatpage_menu(): # Create an unordered list of all flatpages pages = FlatPage.objects.all() menu = '<ul>' for i in range(len(pages)): menu += '<li>'+'<a href="'+pages[i].url+'" title="'+pages[i].title+'">'+pages[i].title+'</a></li>' menu += '</ul>' return menu register.simple_tag(flatpage_menu) import calendar @register.filter def weekdayabbr(value):
import os from django.template import Library from django.conf import settings register = Library() def URL_PREFIX(): return settings.URL_PREFIX register.simple_tag(URL_PREFIX) def STATIC_PREFIX(): return settings.STATIC_PREFIX register.simple_tag(STATIC_PREFIX) @register.filter(name='get_pages') def get_pages(value, arg=''): s = x = '' if arg: x = 'min_support=%s&' % arg if int(value.paginator.num_pages) < 4: for i in range(int(value.paginator.num_pages)): if int(value.number) == int(i)+1: s += '<strong>%s</strong> ' % (int(i)+1) else: s += '<a href="?%spage=%s">%s</a> ' % (x, i+1, i+1) elif int(value.paginator.num_pages)-int(value.number) > 3 and int(value.number) > 4 or int(value.number)-1 > 3 and int(value.number) < 4 or int(value.number) == 4: s = '1 ... <a href="?%spage=%s">%s</a> <strong>%s</strong> <a href="?page=%s">%s</a> ...%s' % (x, value.previous_page_number(), value.previous_page_number(), value.number, value.next_page_number(), value.next_page_number(), value.paginator.num_pages) else: if int(value.number)-1 < 3:
GREEK_LETTERS = \ '[Aa]lpha|[Bb]eta|[Gg]amma|[Dd]elta|[Ee]psilon|[Zz]eta|' + \ '[Ee]ta|[Tt]heta|[Ll]ambda|[Mm]u|[Nn]u|[Pp]i|[Ss]igma|[Tt]au|' + \ '[Pp]hi|[Pp]si|[Cc]hi|[Oo]mega|[Rr]ho|[Xx]i|[Kk]appa' def get_publication(id): pbl = Publication.objects.filter(pk=int(id)) if len(pbl) < 1: return '' return get_template('publications/publication.html').render( Context({'publication': pbl[0]})) def tex_parse(string): def tex_replace(match): return \ sub(r'\^(\w)', r'<sup>\1</sup>', sub(r'\^\{(.*?)\}', r'<sup>\1</sup>', sub(r'\_(\w)', r'<sub>\1</sub>', sub(r'\_\{(.*?)\}', r'<sub>\1</sub>', sub(r'\\(' + GREEK_LETTERS + ')', r'&\1;', match.group(1)))))) return mark_safe(sub(r'\$([^\$]*)\$', tex_replace, escape(string))) register.simple_tag(get_publication) register.filter('tex_parse', tex_parse)
GREEK_LETTERS = \ '[Aa]lpha|[Bb]eta|[Gg]amma|[Dd]elta|[Ee]psilon|[Zz]eta|' + \ '[Ee]ta|[Tt]heta|[Ll]ambda|[Mm]u|[Nn]u|[Pp]i|[Ss]igma|[Tt]au|' + \ '[Pp]hi|[Pp]si|[Cc]hi|[Oo]mega|[Rr]ho|[Xx]i|[Kk]appa' def get_publication(id): pbl = Publication.objects.filter(pk=int(id)) if len(pbl) < 1: return '' pbl[0].links = pbl[0].customlink_set.all() pbl[0].files = pbl[0].customfile_set.all() return get_template('publishing/publication.html').render( Context({'publication': pbl[0]})) def tex_parse(string): string = replace(replace(string, '{', ''), '}', '') def tex_replace(match): return \ sub(r'\^(\w)', r'<sup>\1</sup>', sub(r'\^\{(.*?)\}', r'<sup>\1</sup>', sub(r'\_(\w)', r'<sub>\1</sub>', sub(r'\_\{(.*?)\}', r'<sub>\1</sub>', sub(r'\\(' + GREEK_LETTERS + ')', r'&\1;', match.group(1)))))) return mark_safe(sub(r'\$([^\$]*)\$', tex_replace, escape(string))) register.simple_tag(get_publication) register.filter('tex_parse', tex_parse)
from django.utils.html import escape from django.template import Library from datetime import datetime register = Library() def serving_time(): """ Return the approximate number of years since OCLUG's inception. """ n = datetime.now() nm = (n.year * 12 + n.month) - (1997 * 12 + 3) m = nm % 12 if m > 6: return "%d½ years" % (nm / 12) else: return "%d years" % (nm / 12) serving_time = register.simple_tag(serving_time)
def view_block(context, block_name, *args, **kwargs): if 'admin_view' not in context: return "" admin_view = context['admin_view'] nodes = [] method_name = 'block_%s' % block_name for view in [admin_view] + admin_view.plugins: if hasattr(view, method_name) and callable(getattr(view, method_name)): block_func = getattr(view, method_name) result = block_func(context, nodes, *args, **kwargs) if result and type(result) in (str, unicode): nodes.append(result) if nodes: return ''.join(nodes) else: return "" @register.filter def admin_urlname(value, arg): return 'xadmin:%s_%s_%s' % (value.app_label, value.module_name, arg) static = register.simple_tag(static) @register.simple_tag(takes_context=True) def vendor(context, *tags): return util_vendor(*tags).render()
from django.template import Library register = Library() def admin_media_prefix(): """ Returns the string contained in the setting ADMIN_MEDIA_PREFIX. """ try: from django.conf import settings except ImportError: return '' return settings.ADMIN_MEDIA_PREFIX admin_media_prefix = register.simple_tag(admin_media_prefix)
real_value=field.field.field.empty_label if real_value!="dead channel": real_value="" elif isinstance(field.field.field.widget, RelatedFieldWidgetWrapper): real_value = _display_readonly_related_field(field, adminform) elif hasattr( field.field.field.widget, "choices"): for choice in field.field.field.widget.choices: for value in values: if value == choice[0]: real_value += u'%s<br/>' % choice[1] elif isinstance(field.field.field.widget, AdminFileWidget): if value!=None and value!="": real_value=display_file(value) elif isinstance(field.field.field, forms.BooleanField): real_value = "Yes" if value else "No" else: real_value = value return {'value': mark_safe(real_value)} def display_classname(obj): if hasattr(obj, "original"): classname = obj.original.__class__.__name__.lower() elif hasattr(obj, "formset"): classname = obj.formset.model.__name__.lower() else: classname = obj.__class__.__name__.lower() return classname display_classname = register.simple_tag(display_classname)
from django.template import Library from oioioi.portals.actions import portal_url register = Library() register.simple_tag(portal_url)
from django.template import Library, Node from yazkicom.sitebilgileri.models import Sitebilgi register = Library() def sitebilgileri_menu(): bilgiliste = Sitebilgi.objects.all() menu = '' for i in range(len(bilgiliste)): menu += ''+bilgiliste[i].siteadi+' <br/> '+bilgiliste[i].siteaciklama+' <br/> '+bilgiliste[i].sitelink+' <br/> '+bilgiliste[i].author+' ' return menu register.simple_tag(sitebilgileri_menu)
# -*- coding: utf-8 -*- ''' Template tags for explicit space and newline. Intended to be used with plaintextformat loader. ''' from django.template import Library import re register = Library() # XHTML-XMPP-template compatible. def br(): #return "<br />\n" # XHTML br-inserting is handled otherplace now. return "\n" br = register.simple_tag(br) def ws(): return " " ws = register.simple_tag(ws)
from django.template import Library register = Library() def times_ranked(player, rank=0, num_players=0): if rank > num_players and num_players != 0: return '-' return str(player.times_ranked(rank, num_players)) def high_score(player, num_players=0): return str(player.high_score(num_players)) def low_score(player, num_players=0): return str(player.low_score(num_players)) register.simple_tag(times_ranked) register.simple_tag(high_score) register.simple_tag(low_score)
def activity_stream(context, stream_type, *args, **kwargs): """ Renders an activity stream as a list into the template's context. Streams loaded by stream_type can be the default ones (eg user, actor, etc.) or a user defined stream. Extra args/kwargs are passed into the stream call. :: {% activity_stream 'actor' user %} {% for action in stream %} {% display_action action %} {% endfor %} """ if stream_type == 'model': stream_type = 'model_actions' if not hasattr(Action.objects, stream_type): raise TemplateSyntaxError('Action manager has no attribute: %s' % stream_type) ctxvar = kwargs.pop('as', 'stream') context[ctxvar] = getattr(Action.objects, stream_type)(*args, **kwargs) return '' register.filter(activity_stream) register.filter(is_following) register.tag(display_action) register.tag(follow_url) register.tag(follow_all_url) register.tag(actor_url) register.simple_tag(takes_context=True)(activity_stream)
elif arg3 is None: return string % (arg0, arg1, arg2) elif arg4 is None: return string % (arg0, arg1, arg2, arg3) elif arg5 is None: return string % (arg0, arg1, arg2, arg3, arg4) elif arg6 is None: return string % (arg0, arg1, arg2, arg3, arg4, arg5) else: return string % (arg0, arg1, arg2, arg3, arg4, arg5, arg6) except: return string format.is_safe = True register.simple_tag(format) def make_args(search, page): return gramps.webapp.utils.build_args(search=search, page=page) make_args.is_safe = True register.simple_tag(make_args) def format_color(color): return color[0:3] + color[5:7] + color[9:11] format_color.is_safe = True
block_func = getattr(view, method_name) result = block_func(context, nodes, *args, **kwargs) if result and isinstance(result, cls_str): nodes.append(result) if nodes: return mark_safe(''.join(nodes)) else: return "" @register.filter def admin_urlname(value, arg): return 'xadmin:%s_%s_%s' % (value.app_label, value.model_name, arg) static = register.simple_tag(static) @register.simple_tag(takes_context=True) def vendor(context, *tags): return util_vendor(*tags).render() class BlockcaptureNode(template.Node): """https://chriskief.com/2013/11/06/conditional-output-of-a-django-block/""" def __init__(self, nodelist, varname): self.nodelist = nodelist self.varname = varname def render(self, context): output = self.nodelist.render(context)
</ul> </li> <li>Non-fiction</li> </ul> </ul> """ active_cat = None if id: active_cat = Category.objects.get(id=id) root = Element("ul") for cats in Category.objects.root_categories(): recurse_for_children(cats, root, active_cat) return tostring(root, "utf-8") register.simple_tag(category_tree) class CategoryListNode(Node): """Template Node tag which pushes the category list into the context""" def __init__(self, slug, var, nodelist): self.var = var self.slug = slug self.nodelist = nodelist def render(self, context): if self.slug: try: cat = Category.objects.get(slug__iexact=self.slug)
from django.template import Library register = Library() def filer_staticmedia_prefix(): """ Returns the string contained in the setting FILER_STATICMEDIA_PREFIX. """ try: from .. import settings except ImportError: return '' return settings.FILER_STATICMEDIA_PREFIX filer_staticmedia_prefix = register.simple_tag(filer_staticmedia_prefix)
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 from django.template import Library register = Library() def pourcent(a, b, format='%d'): """ Return the pourcentage of value 'a' in relation to value b. """ return format % (float(a) * 100 / float(b)) paginator_number = register.simple_tag(pourcent)
def paginator_number(cl, i): """ Generates an individual page index link in a paginated list. """ if i == DOT: return u'... ' elif i == cl.page_num: return mark_safe(u'<span class="this-page">%d</span> ' % (i + 1)) else: return mark_safe(u'<a href="%s"%s>%d</a> ' % (escape(cl.get_query_string({PAGE_VAR: i})), (i == cl.paginator.num_pages - 1 and ' class="end"' or ''), i + 1)) paginator_number = register.simple_tag(paginator_number) def pagination(cl): """ Generates the series of links to the pages in a paginated list. """ paginator, page_num = cl.paginator, cl.page_num pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page if not pagination_required: page_range = [] else: ON_EACH_SIDE = 3 ON_ENDS = 2
# nothing in the cache, so we have to generate the feed now out = [] try: doc = parseString(urlopen(FEED_URL).read()) items = doc.getElementsByTagName("item") for i in items: out.append('<div class="develitem">') # parse and convert date to local time tm = i.getElementsByTagName("pubDate")[0].firstChild.data tm = localtime(timegm(strptime(tm, DATE_IN_FORMAT))) out.append(strftime(DATE_OUT_FORMAT, tm)) # Here we are trusting the HTML returned from the rss feed # and displaying it mostly as-is: out.append(' <a href="%s">%s</a>' % ( i.getElementsByTagName("link")[0].firstChild.data, i.getElementsByTagName("title")[0].firstChild.data)) out.append('</div>') except: out = ["Error encountered updating devel feed."] out = "".join(out) # store the result for next time cache.set('devel_feed', out, CACHE_TIMEOUT) return out devel_feed = register.simple_tag(devel_feed)
""" Returns the price as (+$1.00) or (-$1.00) depending on the sign of the price change The currency symbol is set in the settings.py file """ output = "" if option_item.price_change != 0: amount = moneyfmt(abs(option_item.price_change)) if option_item.price_change < 0: output = "(- %s)" % amount if option_item.price_change > 0: output = "(+ %s)" % amount return output register.simple_tag(option_price) def option_total_price(product, option_item): """ Returns the price as (+$1.00) or (-$1.00) depending on the sign of the price change The currency symbol is set in the settings.py file """ if option_item.price_change: val = product.unit_price + option_item.price_change else: val = product.unit_price return moneyfmt(val)
def __init__(self, context_var): self.context_var = context_var def render(self, context): context[self.context_var] = TagsForm(auto_id=False) return '' def do_tagsform(parser, token): bits = token.contents.split() if len(bits)!=3 and bits[1]!="as": raise TemplateSyntaxError("Need as [context variable]") return TagsFormNode(bits[2]) def get_contenttype_kwargs(content_object): """ Gets the basic kwargs necessary for almost all of the following tags. """ kwargs = { 'content_type' : ContentType.objects.get_for_model(content_object).id, 'object_id' : getattr(content_object, 'pk', getattr(content_object, 'id')), } return kwargs def get_add_tags_url(content_object, parent=None): kwargs = get_contenttype_kwargs(content_object) return reverse('tagging_add-tags', kwargs=kwargs) register.tag('tagsform', do_tagsform) register.simple_tag(get_add_tags_url)
register = Library() DOT = '.' def paginator_number(cl,i): """ Generates an individual page index link in a paginated list. """ if i == DOT: return u'... ' elif i == cl.page_num: return mark_safe(u'<span class="this-page">%d</span> ' % (i+1)) else: return mark_safe(u'<a href="%s"%s>%d</a> ' % (escape(cl.get_query_string({PAGE_VAR: i})), (i == cl.paginator.num_pages-1 and ' class="end"' or ''), i+1)) paginator_number = register.simple_tag(paginator_number) def pagination(cl): """ Generates the series of links to the pages in a paginated list. """ paginator, page_num = cl.paginator, cl.page_num pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page if not pagination_required: page_range = [] else: ON_EACH_SIDE = 3 ON_ENDS = 2 # If there are 10 or fewer pages, display links to every page.
try : c = get_definition_with_path(d) if c is not None : d = c except: pass res = r.search( path ) if res is not None : if callable(d): desc = d(res) else: desc = d return '<meta name="description" content="%s"/>' % desc render_post = register.inclusion_tag("posts/post_view.html")(render_post) render_post_with_id = register.inclusion_tag("posts/post_view.html")(render_post_with_id) render_orphan = register.inclusion_tag("posts/orphan_view.html")(render_orphan) register.simple_tag( get_gravatar_md5 ) register.simple_tag( render_categories_list ) register.simple_tag( get_page_description_meta ) register.tag( get_post ) register.tag( get_post_by_comment_id ) register.tag( get_post_category_list ) register.tag( get_post_archives_list ) register.tag( get_comment_archives_list ) register.tag( get_post_tags_list ) register.tag( get_site_links_list )
:return str: Rendered string. """ bits = token.split_contents()[1:] args, kwargs = parse_bits(parser, bits, ['content'], 'args', 'kwargs', tuple(), False, 'adrest_include') return AdrestInclusionNode(False, args, kwargs) adrest_include = register.tag(adrest_include) from adrest.utils.transformers import SmartDjangoTransformer def adrest_jsonify(content, resource, request=None, **kwargs): """ Serialize any object to JSON . :return str: Rendered string. """ transformer = SmartDjangoTransformer return simplejson.dumps( transformer(resource, data=content, request=request).transform(), **(getattr(resource._meta, 'emit_options', {}) or {})) adrest_jsonify = register.simple_tag(adrest_jsonify)
key = sha1('comment_count_%s_%s' % (the_object.__unicode__(), the_object.pk)).hexdigest() cache_count = cache.get(key) if cache_count is None: cache_count = Comment.objects.filter( content_type=the_object.get_ct(), object_pk=smart_unicode(the_object.pk), site__pk=settings.SITE_ID, is_public=True, is_removed=False ).count() cache.set(key, cache_count, 1500) context[self.as_var] = cache_count return "" def DoCacheCommentCount(parser, token): '''{% cache_comment_count [object] as [varname] %} ''' bits = token.contents.split() if len(bits) != 4: raise TemplateSyntaxError, "cache_comment_count takes exactly 3 arguments" elif bits[2] != 'as': raise TemplateSyntaxError, "second argument of cache_comment_count tage must be 'as'" else: return CacheCommentCount(bits[1], bits[3]) register.tag('get_cached_comment_count', DoCacheCommentCount) register.tag('get_comment_count', get_comment_count) register.tag('get_comment_list', get_comment_list) register.tag('get_comment_form', get_comment_form) register.tag('render_comment_form', render_comment_form) register.simple_tag(comment_form_target)