def load(parser, token): """ Loads a custom template tag set. For example, to load the template tags in ``django/templatetags/news/photos.py``:: {% load news.photos %} Can also be used to load an individual tag/filter from a library:: {% load byline from news %} """ bits = token.contents.split() if len(bits) >= 4 and bits[-2] == "from": try: taglib = bits[-1] lib = get_library(taglib) except InvalidTemplateLibrary, e: raise TemplateSyntaxError("'%s' is not a valid tag library: %s" % (taglib, e)) else: temp_lib = Library() for name in bits[1:-2]: if name in lib.tags: temp_lib.tags[name] = lib.tags[name] # a name could be a tag *and* a filter, so check for both if name in lib.filters: temp_lib.filters[name] = lib.filters[name] elif name in lib.filters: temp_lib.filters[name] = lib.filters[name] else: raise TemplateSyntaxError("'%s' is not a valid tag or filter in tag library '%s'" % (name, taglib)) parser.add_library(temp_lib)
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')
def tryload(parser, token): bits = token.contents.split() if len(bits) >= 4 and bits[-2] == "from": try: taglib = bits[-1] lib = get_library(taglib) except InvalidTemplateLibrary as e: return LoadNode() else: temp_lib = Library() for name in bits[1:-2]: if name in lib.tags: temp_lib.tags[name] = lib.tags[name] if name in lib.filters: temp_lib.filters[name] = lib.filters[name] elif name in lib.filters: temp_lib.filters[name] = lib.filters[name] else: return LoadNode() parser.add_library(temp_lib) else: for taglib in bits[1:]: try: lib = get_library(taglib) parser.add_library(lib) except InvalidTemplateLibrary as e: return LoadNode() return LoadNode()
def test_fail_on_parse(self): from django.template import builtins from django.template import Library from django.template import Template def test_not_enough_args(context): return 'this should never ever run' templates = [ "{% test_parse 1 obj.val as var %}", "{% test_parse obj.fn 'string' %}", ] class test_object(object): val = 'string' def fn(self): return 1 register = Library() register.tag('test_parse', ParsedNode('test_parse', '<thing1:int> <thing2:string>( as <asvar:var>)', test_not_enough_args)) builtins.append(register) context = { 'obj':test_object() } templates_cmp = [Template(template) for template in templates] for i in templates_cmp: self.assertRaises(TemplateSyntaxError, i.render, context)
def test_actually_parsing_works(self): from django.template import builtins from django.template import Library from django.template import Template def test_parse(context, thing1, thing2, asvar=None): return u' '.join([str(thing1), thing2, str(asvar)]) templates = [ "{% test_parse 1 obj.val as var %}", "{% test_parse obj.fn 'string' %}", ] class test_object(object): val = 'string' def fn(self): return 1 register = Library() register.tag('test_parse', ParsedNode('test_parse', '<thing1:int> <thing2:string>( as <asvar:var>)', test_parse)) builtins.append(register) context = { 'obj':test_object() } templates_cmp = [Template(template) for template in templates] results = [t.render(context) for t in templates_cmp] self.assertEqual(results[0], '1 string var') self.assertEqual(results[1], '1 string None')
def load(parser, lib, tag='*', name=None, namespace=None, app=None): """ Determine and load tags into parser. If only a parser and lib are provided, it will behave just like Django's built-in {% load %} tag. Additional arguments provide more control over its behavior. Arguments: - parser (required) Template parser to load the tag into. - lib (required) Name of template library to load. - tag If '*', it will load all tags from the given library. If a string is provided, it will load a tag of that name. - name Name to assign to the loaded tag (defaults to the name registered to the template library object). - namespace String to prepend to the name of the tag. - app Tries to load the tag from the given app name. """ try: lib_name = lib lib = Library() if app: module_lib = get_library(app) else: module_lib = get_library(lib_name) lib.tags.update(module_lib.tags) lib.filters.update(module_lib.filters) if tag != '*': lib.tags = {tag: lib.tags[tag]} if name: for tag in lib.tags.keys(): lib.tags[name] = lib.tags[tag] if tag != name: del lib.tags[tag] if namespace: for tag in lib.tags.keys(): lib.tags['%s.%s' % (namespace, tag)] = lib.tags[tag] del lib.tags[tag] parser.add_library(lib) except InvalidTemplateLibrary, e: raise TemplateSyntaxError("'%s' is not a valid tag library: %s" % (lib, e))
def test_empty_does_not_break(self): from django.template import builtins from django.template import Library from django.template import Template def test_empty_values_are_okay(context, *args, **kwargs): self.assertTrue(True) return u'' template = "{% test_parse dne_int dne_str dne_any dne_var %}" register = Library() register.tag('test_parse', ParsedNode('test_parse', '<arg1:int> <arg2:string> <arg3:any> <arg4:var>', test_empty_values_are_okay)) builtins.append(register) context = { } template_obj = Template(template) try: template_obj.render(context) except Exception, e: self.fail("%s was raised when rendering a parsed tag with empty arguments." % str(e))
class FilterRegistrationTests(TestCase): def setUp(self): self.library = Library() def test_filter(self): @self.library.filter def func(): return '' self.assertEqual(self.library.filters['func'], func) def test_filter_parens(self): @self.library.filter() def func(): return '' self.assertEqual(self.library.filters['func'], func) def test_filter_name_arg(self): @self.library.filter('name') def func(): return '' self.assertEqual(self.library.filters['name'], func) def test_filter_name_kwarg(self): @self.library.filter(name='name') def func(): return '' self.assertEqual(self.library.filters['name'], func) def test_filter_call(self): def func(): return '' self.library.filter('name', func) self.assertEqual(self.library.filters['name'], func) def test_filter_invalid(self): msg = "Unsupported arguments to Library.filter: (None, '')" with self.assertRaisesMessage(ValueError, msg): self.library.filter(None, '')
class TagRegistrationTests(TestCase): def setUp(self): self.library = Library() def test_tag(self): @self.library.tag def func(parser, token): return Node() self.assertEqual(self.library.tags['func'], func) def test_tag_parens(self): @self.library.tag() def func(parser, token): return Node() self.assertEqual(self.library.tags['func'], func) def test_tag_name_arg(self): @self.library.tag('name') def func(parser, token): return Node() self.assertEqual(self.library.tags['name'], func) def test_tag_name_kwarg(self): @self.library.tag(name='name') def func(parser, token): return Node() self.assertEqual(self.library.tags['name'], func) def test_tag_call(self): def func(parser, token): return Node() self.library.tag('name', func) self.assertEqual(self.library.tags['name'], func) def test_tag_invalid(self): msg = "Unsupported arguments to Library.tag: (None, '')" with self.assertRaisesMessage(ValueError, msg): self.library.tag(None, '')
""" django-helpdesk - A Django powered ticket tracker for small enterprise. templatetags/load_helpdesk_settings.py - returns the settings as defined in django-helpdesk/helpdesk/settings.py """ from django.template import Library from helpdesk import settings as helpdesk_settings_config def load_helpdesk_settings(request): # try: return helpdesk_settings_config # except Exception, e: # import sys # print >> sys.stderr, "'load_helpdesk_settings' template tag (django-helpdesk) crashed with following error:" # print >> sys.stderr, e # return '' register = Library() register.filter('load_helpdesk_settings', load_helpdesk_settings)
# TAKEN FROM http://djangosnippets.org/snippets/1568/ from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers register = Library() class ViewNode(Node): def __init__(self, url_or_view, args, kwargs): self.url_or_view = url_or_view self.args = args self.kwargs = kwargs def render(self, context): if 'request' not in context: return "" request = context['request'] url_or_view = Variable(self.url_or_view).resolve(context) try: urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) view, args, kwargs = resolver.resolve(url_or_view) except: view = urlresolvers.get_callable(url_or_view, True) args = [Variable(arg).resolve(context) for arg in self.args] kwargs = {} for key, value in self.kwargs.items(): kwargs[key] = Variable(value).resolve(context)
__copyright__ = '2014-2016 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ( 'get_fobi_plugin', 'get_fobi_form_handler_plugin_custom_actions', 'get_fobi_form_wizard_handler_plugin_custom_actions', 'get_form_field_type', 'get_form_hidden_fields_errors', 'has_edit_form_entry_permissions', 'render_auth_link', 'render_fobi_forms_list', ) theme = get_theme(request=None, as_instance=True) register = Library() # ***************************************************************************** # ***************************************************************************** # ***************************************************************************** # **************************** General Fobi tags ****************************** # ***************************************************************************** # ***************************************************************************** # ***************************************************************************** # ***************************************************************************** # ******************************* Plugin specific ***************************** # ***************************************************************************** class GetFobiPluginNode(Node):
import os import commands from django.template import Library, Node, TemplateSyntaxError register = Library() global version_info_cached version_info_cached=None class VersionsNode(Node): def __init__(self): pass def render(self, context): global version_info_cached if version_info_cached: #raise TemplateSyntaxError("versions tag does seem to be being called.") return version_info_cached else: allinfo="" user = os.environ['USER'] host = os.environ['HOSTNAME'] allinfo+="%s@%s, " % (user,host) (status, output) = commands.getstatusoutput("rpm -q httpd") allinfo+="%s, " % output.strip() (status, output) = commands.getstatusoutput("rpm -q mod_python") allinfo+="%s, " % output.strip() (status, output) = commands.getstatusoutput("rpm -q python")
"""Tags for manipulating brands on templates.""" from django.core.cache import cache from django.template import Library from django.template import Node from satchmo.product.brand.models import Brand register = Library() class BrandListNode(Node): """Template Node tag which pushes the brand list into the context""" def __init__(self, var, nodelist): self.var = var self.nodelist = nodelist def render(self, context): brands = Brand.objects.active() context[self.var] = brands context.push() context[self.var] = brands output = self.nodelist.render(context) context.pop() return output def do_brandlistnode(parser, token): """Push the brand list into the context using the given variable name. Sample usage:: {% brand_list as var %}
from django.conf import settings from django.contrib.admin.util import lookup_field, display_for_field, label_for_field from django.contrib.admin.views.main import ALL_VAR, EMPTY_CHANGELIST_VALUE from django.contrib.admin.views.main import ORDER_VAR, ORDER_TYPE_VAR, PAGE_VAR, SEARCH_VAR from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.forms.forms import pretty_name from django.utils import formats from django.utils.html import escape, conditional_escape from django.utils.safestring import mark_safe from django.utils.text import capfirst from django.utils.translation import ugettext as _ from django.utils.encoding import smart_unicode, force_unicode from django.template import Library 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)
from django.template import Library, Node, Variable from django.template.loader import select_template from django.template import RequestContext register = Library() class PromotionNode(Node): def __init__(self, promotion): self.promotion_var = Variable(promotion) def render(self, context): promotion = self.promotion_var.resolve(context) template = select_template( [promotion.template_name(), 'promotions/default.html']) args = {'promotion': promotion} args.update(**promotion.template_context(request=context['request'])) ctx = RequestContext(context['request'], args) return template.render(ctx) def get_promotion_html(parser, token): _, promotion = token.split_contents() return PromotionNode(promotion) register.tag('render_promotion', get_promotion_html)
Takes an optional argument to specify the name of a filter to use. """ if arg is not None: return mark_safe(formatter(value, filter_name=arg)) return mark_safe(formatter(value)) apply_markup.is_safe = True def smartypants(value): """ Applies SmartyPants to a piece of text, applying typographic niceties. Requires the Python SmartyPants library to be installed; see http://web.chad.org/projects/smartypants.py/ """ try: from smartypants import smartyPants except ImportError: if settings.DEBUG: raise template.TemplateSyntaxError("Error in smartypants filter: the Python smartypants module is not installed or could not be imported") return value else: return mark_safe(smartyPants(value)) register = Library() register.filter(apply_markup) register.filter(smartypants)
from django.template import Library from lablog.models import Event register = Library() # if no scheduling information is given then we always assume past events def time_since_until(date, schedule=Event.SCHEDULE_PAST, time=None): return time_since_until_format(date, schedule, time) register.simple_tag(time_since_until) ' the logic behind "time_since_until"' def time_since_until_format(date, schedule=Event.SCHEDULE_PAST, time=None): from django.contrib.humanize.templatetags.humanize import naturalday # combine date and time, if time is given. Some models provide "date" # already in datetime format if time: date = datetime.datetime.combine(date, time) time_since = timesince(date) time_until = timeuntil(date) human_date_orig = naturalday(date) human_date = human_date_orig + ' - ' # django 1.1.x zero_strg = '0 minutes'
from django.template import Library, Node, resolve_variable from django.template.defaultfilters import stringfilter from django.utils.safestring import mark_safe from django.utils.text import normalize_newlines from project.ajapaik import settings register = Library() class AddGetParameter(Node): def __init__(self, values): self.values = values def render(self, context): req = resolve_variable('request', context) params = req.GET.copy() for key, value in self.values.items(): params[key] = value.resolve(context) return '?%s' % params.urlencode() @register.tag def add_get(parser, token): pairs = token.split_contents()[1:] values = {} for pair in pairs: s = pair.split('=', 1) values[s[0]] = parser.compile_filter(s[1]) return AddGetParameter(values)
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.
""" Provide processing for pipeline views """ import re from django.utils.safestring import mark_safe from django.template import Library register = Library() # pylint: disable=invalid-name INMIA = '<span class="input-missing" title="Missing input: {}" data-toggle="tooltip" data-placement="bottom">{}</span>' INOK = '<span class="input" title="{}" data-toggle="tooltip" data-placement="bottom">{}</span>' INBIN = '<span class="bin" title="{}" data-toggle="tooltip" data-placement="bottom">{}</span>' OUT = '<span class="output" data-toggle="tooltip" data-placement="bottom" title="{}">{}</span>' OUTMIA = '<span class="input-missing" data-toggle="tooltip" data-placement="bottom" title="Missing output: {}">{}</span>' def replace_helper(text, fn, template, name): to_replace = r'(^| |=){}( |$)'.format(fn) return re.sub(to_replace, r'\1' + template.format(fn, name) + r'\2', text) @register.filter("process_command") def command(job): """processes the command by highlighting the input and output files""" text = job.debug_text input_fn = job.input_fn output_fn = job.output_fn # keep track of which files are inputs and which are outputs # set lookup has average case O(1)
import urlparse from django.template import Library from django.template.defaulttags import URLNode, url from django.contrib.sites.models import Site from django.template import Token from django.template import Variable import os register = Library() class RelativeURLNode(URLNode): """Only works with python 2.6 """ request_path = None def render(self, context): req = Variable(self.request_path).resolve(context).rpartition('/')[0] path = super(RelativeURLNode, self).render(context) return os.path.relpath(path, req) def relurl(parser, token, node_cls=RelativeURLNode): """Use like the url templatetag, but provide the request path as the first argument and this templatetag will return a relative url.""" old_token = token contents = old_token.split_contents() request_path = contents.pop(1) new_token = Token(old_token.token_type, ' '.join(contents)) node_instance = url(parser, new_token) node_instance.request_path = request_path
from django.contrib.admin.views.main import ALL_VAR, EMPTY_CHANGELIST_VALUE from django.contrib.admin.views.main import ORDER_VAR, ORDER_TYPE_VAR, PAGE_VAR, SEARCH_VAR from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.utils import dateformat from django.utils.html import escape, conditional_escape from django.utils.text import capfirst from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from django.utils.formats import get_format from django.utils.encoding import smart_unicode, smart_str, force_unicode from django.template import Library import datetime register = Library() quo_esc = lambda x: x.replace("'", r"\'") def thumbnails_for_result(cl, result, form): """ Basically does the same thing as django's items_for_result, but makes all the items fit in one <td> element instead of separate elements for each field """ first = True pk = cl.lookup_opts.pk.attname for field_name in cl.list_display: row_class = '' try: f = cl.lookup_opts.get_field(field_name)
# django imports from django.core.cache import cache from django.template import Library, Node, TemplateSyntaxError from django.utils.translation import ugettext as _ # portlets imports import portlets.utils from portlets.models import Slot # lfs imports import lfs.core.utils register = Library() class SlotsInformationNode(Node): """ """ def render(self, context): request = context.get("request") object = context.get("category") or context.get( "product") or context.get("page") if object is None: object = lfs.core.utils.get_default_shop(request) slots = cache.get("slots") if slots is None: slots = Slot.objects.all() cache.set("slots", slots) for slot in slots:
from django.template import Library, Node, TemplateSyntaxError from uuid import uuid4 register = Library() class UUIDNode(Node): """ Implements the logic of this tag. """ def __init__(self, var_name): self.var_name = var_name def render(self, context): context[self.var_name] = str(uuid4()) return '' def do_uuid(parser, token): """ The purpose of this template tag is to generate a random UUID and store it in a named context variable. Sample usage: {% uuid var_name %} var_name will contain the generated UUID """ try: tag_name, var_name = token.split_contents() except ValueError: raise TemplateSyntaxError("%r tag requires exactly one argument" %
import urlparse from django.template import Library from django.template.defaulttags import URLNode, url from django.contrib.sites.models import Site register = Library() class AbsoluteURLNode(URLNode): def render(self, context): path = super(AbsoluteURLNode, self).render(context) domain = "http://%s" % Site.objects.get_current().domain return urlparse.urljoin(domain, path) def absurl(parser, token, node_cls=AbsoluteURLNode): """Just like {% url %} but ads the domain of the current site.""" node_instance = url(parser, token) return node_cls(view_name=node_instance.view_name, args=node_instance.args, kwargs=node_instance.kwargs, asvar=node_instance.asvar) absurl = register.tag(absurl)
from django.template import Library 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)))
from django.db import models from django.template import Library from django.contrib.admin.templatetags.admin_list import result_headers, _boolean_icon try: from django.contrib.admin.utils import lookup_field, display_for_field, label_for_field except ImportError: from categories.editor.utils import lookup_field, display_for_field, label_for_field from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE from django.core.exceptions import ObjectDoesNotExist from django.utils.encoding import smart_unicode, force_unicode from django.utils.html import escape, conditional_escape from django.utils.safestring import mark_safe from categories.editor import settings register = Library() TREE_LIST_RESULTS_TEMPLATE = 'admin/editor/tree_list_results.html' if settings.IS_GRAPPELLI_INSTALLED: TREE_LIST_RESULTS_TEMPLATE = 'admin/editor/grappelli_tree_list_results.html' def items_for_tree_result(cl, result, form): """ Generates the actual list of data. """ first = True pk = cl.lookup_opts.pk.attname for field_name in cl.list_display: row_class = '' try:
# -*- coding: utf8 -*- from django.template import Library from blog.models import Post, Category, Tag from account.models import UserSettings register = Library() # use for sidebar widgets @register.inclusion_tag('widgets.html', takes_context=True) def widgets(context): context['categories'] = Category.all() context['tags'] = Tag.all() context['archives'] = Post.getArchives() context['settings'] = UserSettings.getByCurrentUser() return context """ def show_widgets(parser, token): # {% widgets %} return Widgets() class Widgets(template.Node): def render(self, context): context['categories'] = Category.all().order('-post_count') context['tags'] = Tag.all() context['archives'] = Post.getArchives() return '' register.tag('widgets', show_widgets) """
import math, re from django.template import Library, Node, TemplateSyntaxError, VariableDoesNotExist, resolve_variable from django.conf import settings register = Library() ''' Created using the tutorial at: http://ben.timby.com/?p=51 Minor modifications made to work with our project ''' # information common to all star strips DIV_TEMPLATE = "<div id=\"star_strip_%s\">" END_DIV_TEMPLATE = "</div>" IMG_TEMPLATE = "<img border=\"0\" src=\"%s\" alt=\"%s\"/>" EX_IMG_TEMPLATE = "<img onmouseover=\"javascript: hoverStar(%s, %s);\" onmouseout=\"javascript: restoreStar(%s);\" onclick=\"javascript: clickStar('%s', %s, %s);\" style=\"border: 0;\" src=\"%s\" alt=\"%s\"/>" # the stars values and associated images and alts STARS = { 0.0: ("No Star", "images/star_0.0.png"), 0.25: ("Quarter Star", "images/star_0.25.gif"), 0.5: ("Half Star", "images/star_0.5.png"), 0.75: ("Three Quarter Star", "images/star_0.75.gif"), 1.0: ("Full Star", "images/star_1.0.png") } # ways this can be rounded ROUNDERS = { "full": 1, "half": 2,
from django.template import Library from django.template.loader import render_to_string from jinja2 import nodes from jinja2.ext import Extension register = Library() class MerchantExtension(Extension): tags = set(['render_integration']) def parse(self, parser): stream = parser.stream lineno = stream.next().lineno obj = parser.parse_expression() call_node = self.call_method('render_integration', args=[obj]) return nodes.Output([call_node]).set_lineno(lineno) @classmethod def render_integration(self, obj): form_str = render_to_string(obj.template, {'integration': obj}) return form_str register.tag(MerchantExtension)
# PYTHON IMPORTS import os import re from time import gmtime # DJANGO IMPORTS from django.template import Library, Node, Variable, VariableDoesNotExist, TemplateSyntaxError from django.conf import settings from django.core.files import File # FILEBROWSER IMPORTS from filebrowser.settings import VERSIONS, PLACEHOLDER, SHOW_PLACEHOLDER, FORCE_PLACEHOLDER from filebrowser.base import FileObject from filebrowser.sites import get_default_site register = Library() import logging class VersionNode(Node): def __init__(self, src, suffix): self.src = src self.suffix = suffix def render(self, context): try: version_suffix = self.suffix.resolve(context) source = self.src.resolve(context) except VariableDoesNotExist: return "" if version_suffix not in VERSIONS: return "" # FIXME: should this throw an error?
from django.contrib.admin.utils import unquote from django.template import Library, Node, Variable, TemplateSyntaxError from django.template.loader import get_template from django.conf import settings from django.utils.translation import ugettext as _ from django.utils.http import urlquote from django.utils.encoding import iri_to_uri, force_text from django.utils.html import escape from django.utils.text import capfirst from freppledb.common.models import User from freppledb import VERSION MAX_CRUMBS = 10 register = Library() variable_title = Variable("title") variable_request = Variable("request") variable_popup = Variable("is_popup") # # A tag to create breadcrumbs on your site # class CrumbsNode(Node): r''' A generic breadcrumbs framework. Usage in your templates: {% crumbs %}
# -*- coding: utf-8 -*- from django.db.models import Count from django.template import Library, Node from problemas.models import Problema, ProblemaUtilizado register = Library() class ProblemasMaisUtilizadosNode(Node): def render(self, context): context['problemas_utilizados'] = [] problemas_utilizados = ProblemaUtilizado.objects.all().values('problema').annotate(Count('problema')).order_by('-problema__count')[:5] problemas = [] for problema in problemas_utilizados: problemas.append(Problema.objects.get(pk=problema['problema'])) context['problemas_utilizados'] = sorted(problemas, key=lambda a: a.utilizacoes, reverse=True) return '' def get_problemas_mais_utilizados(parser, token): return ProblemasMaisUtilizadosNode() get_problemas_mais_utilizados = register.tag(get_problemas_mais_utilizados)
''' Django notifications template tags file ''' # -*- coding: utf-8 -*- from distutils.version import StrictVersion # pylint: disable=no-name-in-module,import-error from django import get_version from django.template import Library from django.utils.html import format_html try: 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(context): user = user_context(context) if not user: return '' return user.notifications.unread().exclude(status="待发送").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
from django.template import Library from goflow.runtime.models import WorkItem register = Library() def mywork(user): ''' Display the worklist of a user as a table. The template *goflow/workitems.html* is used for rendering. Usage:: {% mywork user %} settings required:: MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', ... ) **Tip** this can be used instead, if *workitems* variable is available in the context:: {% include "goflow/workitems.html" %} when using *render_to_response* shortcut, don't forget to add a *RequestContext* as following::
from django.template import Library from random_line import random_line register = Library() def random_quote(filename): """ Filter that reads a file and returns one line at random, split into two pieces (quote and author) as a list. Usage: 'diytarot/files/sayings.txt'|random_quote """ quote = random_line(filename) divided = quote.split('~') if len(divided) > 0: return divided else: return [ "OH MY GOD WHO'S FLYING THIS THING!?!!", "..oh right, that would be me." ] register.filter(random_quote)
import math, re from django.template import Library, Node, TemplateSyntaxError, VariableDoesNotExist, resolve_variable from django.conf import settings register = Library() ''' Created using the tutorial at: http://ben.timby.com/?p=51 Minor modifications made to work with our project ''' # information common to all star strips DIV_TEMPLATE = "<div id=\"star_strip_%s\">" END_DIV_TEMPLATE = "</div>" IMG_TEMPLATE = "<img border=\"0\" src=\"%s\" alt=\"%s\"/>" EX_IMG_TEMPLATE = "<img onmouseover=\"javascript: hoverStar(%s, %s);\" onmouseout=\"javascript: restoreStar(%s);\" onclick=\"javascript: clickStar('%s', %s, %s);\" style=\"border: 0;\" src=\"%s\" alt=\"%s\"/>" # the stars values and associated images and alts STARS = { 0.0: ("No Star", "images/star_0.0.png"), 0.25: ("Quarter Star", "images/star_0.25.gif"), 0.5: ("Half Star", "images/star_0.5.png"), 0.75: ("Three Quarter Star", "images/star_0.75.gif"), 1.0: ("Full Star", "images/star_1.0.png") } # ways this can be rounded ROUNDERS = {"full": 1, "half": 2, "quarter": 4} # command patterns CMD_PATTERN = re.compile("^show_stars (.*) of (\d*) round to (%s)$" %
from django.template import Context, Library, RequestContext from django.template import resolve_variable register = Library() def textile(value): try: import textile except ImportError: return value else: return textile.textile(value, encoding='utf-8') register.filter(textile)
from django.apps import apps from django.template import Library register = Library() if apps.is_installed('django.contrib.staticfiles'): from django.contrib.staticfiles.templatetags.staticfiles import static else: from django.templatetags.static import static static = register.simple_tag(static)
from django.template import Library import re register = Library() r_nofollow = re.compile('<a (?![^>]*nofollow)') s_nofollow = '<a rel="nofollow" ' def nofollow(value): return r_nofollow.sub(s_nofollow, value) register.filter(nofollow)
from astrobin import utils from astrobin.enums import SubjectType from astrobin.gear import is_gear_complete, get_correct_gear from astrobin.models import GearUserInfo, UserProfile, Image from astrobin.services.utils_service import UtilsService from astrobin.utils import get_image_resolution, decimal_to_hours_minutes_seconds, decimal_to_degrees_minutes_seconds from astrobin_apps_donations.templatetags.astrobin_apps_donations_tags import is_donor from astrobin_apps_premium.templatetags.astrobin_apps_premium_tags import is_premium_2020, is_premium, is_ultimate_2020, \ is_lite, is_any_ultimate, is_free, is_lite_2020 from astrobin_apps_premium.utils import premium_get_valid_usersubscription from astrobin_apps_remote_source_affiliation.services.remote_source_affiliation_service import \ RemoteSourceAffiliationService from astrobin_apps_users.services import UserService register = Library() @register.filter def split(value, arg): return value.split(arg) @register.filter def startswith(x, y): return x.startswith(y) @register.simple_tag def current(request, pattern): import re
import re from django.template import Node, Variable, VariableNode, _render_value_in_context from django.template import TemplateSyntaxError, TokenParser, Library from django.template import TOKEN_TEXT, TOKEN_VAR from django.utils import translation from django.utils.encoding import force_unicode register = Library() class GetAvailableLanguagesNode(Node): def __init__(self, variable): self.variable = variable def render(self, context): from django.conf import settings context[self.variable] = [(k, translation.ugettext(v)) for k, v in settings.LANGUAGES] return '' class GetCurrentLanguageNode(Node): def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = translation.get_language() return '' class GetCurrentLanguageBidiNode(Node): def __init__(self, variable): self.variable = variable
from django.template import Library, Template, Variable from django.conf import settings from django.template.loader import get_template from django.template.loader_tags import ExtendsNode, IncludeNode, ConstantIncludeNode, BlockNode from django.contrib.auth.models import AnonymousUser, User from tendenci.apps.boxes.models import Box from tendenci.core.perms.utils import get_query_filters from tendenci.core.site_settings.models import Setting from tendenci.core.site_settings.forms import build_settings_form from tendenci.core.site_settings.utils import get_setting from tendenci.core.theme.template_loaders import get_default_template from tendenci.core.theme.utils import get_theme_template register = Library() class ThemeExtendsNode(ExtendsNode): must_be_first = False def __init__(self, nodelist, parent_name, parent_name_expr): self.parent_name = parent_name self.parent_name_expr = parent_name_expr self.nodelist = nodelist self.blocks = dict([(n.name, n) for n in nodelist.get_nodes_by_type(BlockNode)]) def get_parent(self, context): if self.parent_name_expr: self.parent_name = self.parent_name_expr.resolve(context) parent = unicode(self.parent_name)
type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"> </embed> </object> ''' def do_youtube(parser, token): try: tag_name, id_ = token.split_contents() except ValueError: raise TemplateSyntaxError, "%r tag requires 1 argument" % \ token.contents.split()[0] return YoutubeNode(id_) class YoutubeNode(Node): def __init__(self, id_): self.id = Variable(id_) def render(self, context): try: actual_id = self.id.resolve(context) except VariableDoesNotExist: actual_id = self.id t = Template(TEMPLATE) c = Context({'id': actual_id}, autoescape=context.autoescape) return t.render(c) register = Library() register.tag('youtube', do_youtube)
"Default variable filters" from django.template import resolve_variable, Library from django.conf import settings from django.utils.translation import gettext import re import random as random_module register = Library() ####################### # STRING DECORATOR # ####################### def smart_string(obj): # FUTURE: Unicode strings should probably be normalized to a specific # encoding and non-unicode strings should be converted to unicode too. # if isinstance(obj, unicode): # obj = obj.encode(settings.DEFAULT_CHARSET) # else: # obj = unicode(obj, settings.DEFAULT_CHARSET) # FUTURE: Replace dumb string logic below with cool unicode logic above. if not isinstance(obj, basestring): obj = str(obj) return obj def stringfilter(func): """ Decorator for filters which should only receive strings. The object passed
from django.template import Library, Node, NodeList, Variable,\ TemplateSyntaxError, VariableDoesNotExist register = Library() class RangeNode(Node): def __init__(self, var_name, start, end, step, nodelist_loop): self.var_name = var_name self.nodelist_loop = nodelist_loop try: self.start = int(start) except ValueError: self.start = Variable(start) try: self.end = int(end) except ValueError: self.end = Variable(end) try: self.step = int(step) except ValueError: self.step = Variable(step) def __iter__(self): for node in self.nodelist_loop: yield node def render(self, context): nodelist = NodeList()
from django.contrib.auth.models import User from django.urls import reverse from django.core.cache import cache from django.conf import settings from django.utils.translation import ugettext_lazy as _ from tendenci.apps.base.template_tags import parse_tag_kwargs from tendenci.apps.base.utils import url_exists, google_cmap_sign_url from tendenci.apps.profiles.models import Profile from tendenci.apps.files.cache import FILE_IMAGE_PRE_KEY from tendenci.apps.files.utils import generate_image_cache_key from tendenci.apps.site_settings.utils import get_setting from tendenci.apps.theme.templatetags.static import static register = Library() GOOGLE_SMAPS_BASE_URL = 'https://maps.googleapis.com/maps/api/staticmap' class GoogleCMapsURL(Node): def __init__(self, location, origin=None, **kwargs): self.size = kwargs.get("size", "200x200") self.markers = kwargs.get("markers", 'color:red|label:A') self.markers_origin = kwargs.get("markers_origin", 'color:green|label:B') self.zoom = kwargs.get("zoom", None) self.location = Variable(location) if origin: self.origin_point = Variable(origin) else: self.origin_point = None def render(self, context):
import re import copy from django.template import Node, NodeList, TemplateSyntaxError, Library, Variable, Context, VariableDoesNotExist from django.template.loader import get_template from django.conf import settings register = Library() class TableFromCubeNode(Node): def __init__(self, cube, dimensions, filepath): self.filepath = filepath self.dimensions, self.cube = dimensions, cube def render(self, context): #resolve filename matched = re.match('(?P<quote>"|\')(?P<literal>\w+)(?P=quote)', self.filepath) if matched: filepath = matched.group('literal') else: try: filepath = Variable(self.filepath).resolve(context) except VariableDoesNotExist: if settings.DEBUG: return "[couldn't resolve file path]" else: return '' #resolve cube from context
from django.template import Library, Node, Variable, TemplateSyntaxError from django.conf import settings from django.db import models, connections from django.utils.translation import gettext as _ from django.utils.http import urlquote from django.utils.encoding import iri_to_uri, force_text from django.utils.html import escape from django.utils.safestring import mark_safe from django.utils.text import capfirst from freppledb.common.models import User from freppledb import VERSION MAX_CRUMBS = 10 register = Library() variable_title = Variable("title") variable_request = Variable("request") variable_popup = Variable("is_popup") # # A tag to create breadcrumbs on your site # class CrumbsNode(Node): r""" A generic breadcrumbs framework. Usage in your templates: {% crumbs %}
"get_fobi_form_handler_plugin_custom_actions", "get_form_field_type", "get_form_hidden_fields_errors", "has_edit_form_entry_permissions", "render_auth_link", ) from django.template import Library, TemplateSyntaxError, Node from django.conf import settings from django import forms from django.utils.translation import ugettext_lazy as _ from django.forms.util import ErrorDict from fobi.settings import DISPLAY_AUTH_LINK register = Library() # ***************************************************************************** # ***************************************************************************** # ***************************************************************************** # **************************** General Fobi tags ****************************** # ***************************************************************************** # ***************************************************************************** # ***************************************************************************** class GetFobiPluginNode(Node): """ Node for ``get_fobi_plugin`` tag. """
""" ADREST inclusion tags. """ from django.template import Library, VariableDoesNotExist from django.template.base import TagHelperNode, parse_bits from django.template.loader import get_template register = Library() # Fix django templatetags module loader __path__ = "" class AdrestInclusionNode(TagHelperNode): """ Service class for tags. """ def render(self, context): """ Render node. :return str: Rendered string. """ try: args, ctx = self.get_resolved_arguments(context) target = args[0] if not target: return '' ctx['content'] = target except VariableDoesNotExist: return ''
#!/usr/bin/python # -*- coding: utf-8 -*- from django.template import Library from django.template.defaultfilters import stringfilter from django.utils.html import conditional_escape from django.utils.safestring import mark_safe import re register = Library() @stringfilter def spacify(value, autoescape=None): if autoescape: esc = conditional_escape else: esc = lambda x: x return mark_safe(re.sub(' ', '&'+'nbsp; ', esc(value))) spacify.needs_autoescape = True register.filter(spacify)
from django.core.serializers import serialize from django.db.models.query import QuerySet from django.template import Library import json register = Library() def jsonify(object): if isinstance(object, QuerySet): return serialize('json', object) return json.dumps(object) register.filter('jsonify', jsonify)
from django.template import Variable, Library from django.conf import settings from django.utils.translation import gettext, ngettext, get_language register = Library() from djprognosys.localdates.local_dateformat import format, time_format ################### # DATES # ################### def ldate(value, arg=None): "Formats a date according to the given format" if not value: return '' if arg is None: arg = settings.DATE_FORMAT return format(value, arg, get_language()) def ltime(value, arg=None): "Formats a time according to the given format" if value in (None, ''): return '' if arg is None: arg = settings.TIME_FORMAT return time_format(value, arg, get_language()) # below here nothing works def ltimesince(value, arg=None):
from forum.models import Thread, Post from django.utils.translation import ugettext as _ from django.template import Library, Node, TemplateSyntaxError, Variable register = Library() def forum_latest_thread_activity(parser, token): """ {% forum_latest_thread_activity [number] as [context_var] %} """ bits = token.contents.split() if len(bits) not in (1, 2, 4): raise TemplateSyntaxError('%s tag requires none, one or three arguments' % bits[0]) if bits[2] != 'as': raise TemplateSyntaxError("Second argument to %s tag must be 'as'" % bits[0]) if not bits[1]: bits[1] = 5 # Default number of items if not bits[3]: bits[3] = 'latest_thread_activity' return ForumLatestThreadsNode(bits[1], bits[3]) class ForumLatestThreadsNode(Node): def __init__(self, number, context_var): self.number = int(number) - 1 self.context_var = context_var def render(self, context): context[self.context_var] = Thread.objects.select_related().order_by('-latest_post_time')[:self.number] return '' def forum_latest_posts(parser, token):
# -*- 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, loader register = Library() @register.simple_tag() def render_nested(template, context=None): return loader.get_template(template).render(context or {})
from django.template import Node from django.template import Library from vendor.timezones.utilities import localtime_for_timezone register = Library() def localtime(value, timezone): return localtime_for_timezone(value, timezone) register.filter("localtime", localtime)
from django import template from django.template import Library, Node from django.core.urlresolvers import reverse from reporting import site register = Library() class ReportUrlNode(template.Node): report_path = None def __init__(self, report_path): self.report_path = template.Variable(report_path) def render(self, context): report_path = self.report_path.resolve(context) root_url = reverse('reporting_root', args=['']) report_url = site.get_report_by_path(report_path)['url'] request = context['request'] return root_url + report_url + '?' + request.META['QUERY_STRING'] def do_get_report_url(parser, token): try: parts = token.split_contents() report_path = parts[1] except KeyError: