def add_library(self, library): wrapped_library = Library() wrapped_library.filters = library.filters for name, tag_compiler in library.tags.items(): wrapped_library.tags[name] = self.wrap_compile_function( name, tag_compiler) self.parser.add_library(wrapped_library)
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)
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 %} """ # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments bits = token.contents.split() if len(bits) >= 4 and bits[-2] == "from": try: taglib = bits[-1] lib = get_library(taglib) except InvalidTemplateLibrary as 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) else: for taglib in bits[1:]: # add the library to the parser try: lib = get_library(taglib) parser.add_library(lib) except InvalidTemplateLibrary as e: raise TemplateSyntaxError("'%s' is not a valid tag library: %s" % (taglib, e)) return LoadNode()
from django.template.base import Library, TextNode register = Library() def do_tag3(parser, token): return TextNode('<app 1 lib 3 tag 3>') register.tag('tag3', do_tag3)
import os from django.template.loader_tags import ExtendsNode, IncludeNode, BlockContext, BlockNode, ConstantIncludeNode from django.template.loader import get_template import django if django.VERSION[1] >= 3: # >= 1.3 from django.template.base import Library, Node, TextNode from django.template.base import TemplateSyntaxError, TemplateDoesNotExist from django.template.loader_tags import BaseIncludeNode else: # <= 1.2 from django.template import Library, Node, TextNode from django.template import TemplateSyntaxError, TemplateDoesNotExist from django.template import Node as BaseIncludeNode register = Library() BLOCK_CONTEXT_KEY = 'block_context' class ExtendsNode_v2(ExtendsNode): must_be_first = True def __init__(self, nodelist, varlist, template_dirs=None): self.nodelist = nodelist self.varlist = varlist self.template_dirs = template_dirs self.blocks = dict([(n.name, n) for n in nodelist.get_nodes_by_type(BlockNode)]) def __repr__(self): return "<ExtendsNode_v2: extends %s>" % \ ' '.join([ var['type'] == 'var' and var['value'].token or var['value'] for var in self.varlist ])
from django.template.base import TemplateSyntaxError, TemplateDoesNotExist, Variable from django.template.base import Library, Node, TextNode from django.template.context import Context from django.template.defaulttags import token_kwargs from django.template.loader import get_template from django.conf import settings from django.utils.safestring import mark_safe register = Library() BLOCK_CONTEXT_KEY = 'block_context' class ExtendsError(Exception): pass class BlockContext(object): def __init__(self): # Dictionary of FIFO queues. self.blocks = {} def add_blocks(self, blocks): for name, block in blocks.iteritems(): if name in self.blocks: self.blocks[name].insert(0, block) else: self.blocks[name] = [block] def pop(self, name): try: return self.blocks[name].pop() except (IndexError, KeyError):
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP import random as random_module try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.4 fallback. from django.template.base import Variable, Library from django.conf import settings from django.utils import formats from django.utils.encoding import force_unicode, iri_to_uri from django.utils.html import conditional_escape from django.utils.safestring import mark_safe, SafeData from django.utils.translation import ugettext, ungettext register = Library() ####################### # STRING DECORATOR # ####################### def stringfilter(func): """ Decorator for filters which should only receive unicode objects. The object passed as the first positional argument will be converted to a unicode object. """ def _dec(*args, **kwargs): if args: args = list(args) args[0] = force_unicode(args[0])
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging from classytags.arguments import Argument, StringArgument, ChoiceArgument from classytags.core import Options from django.template.base import Library from classytags.helpers import InclusionTag from django.template.defaultfilters import yesno from adminlinks.templatetags.utils import (context_passes_test, get_admin_site, get_registered_modeladmins, _admin_link_shortcut, _add_link_to_context, _add_custom_link_to_context) register = Library() logger = logging.getLogger(__name__) class BaseAdminLink(object): """ Class for mixing into other classes to provide :meth:`~adminlinks.templatetags.adminlinks_buttons.BaseAdminLink.is_valid`, allowing subclasses to test the incoming data and react accordingly:: class MyContextHandler(BaseAdminLink): def get_context(self, context, obj): assert self.is_valid(context, obj) == True Also provides :attr:`~adminlinks.templatetags.adminlinks_buttons.BaseAdminLink.base_options` suitable for using in classy tags.
# -*- coding: utf-8 -*- from classytags.arguments import Flag, StringArgument from classytags.core import Options from django.template.base import Library from classytags.helpers import InclusionTag from adminlinks.templatetags.utils import (context_passes_test, get_admin_site, get_registered_modeladmins, _resort_modeladmins) register = Library() class AdminlinksToolbar(InclusionTag): template = 'adminlinks/toolbar.html' options = Options( Flag('with_labels', true_values=['1', 'true', 'yes', 'on'], false_values=['0', 'false', 'no', 'off'], case_sensitive=False, default=True), StringArgument('admin_site', required=False, default='admin'), ) def get_context(self, context, with_labels, admin_site): """ Updates the *existing* context by putting a list of applicable modeladmins into `app_list` assuming the argument `admin_site` resolved into an AdminSite instance. Always returns the existing context. """
def import_taglib(parser, token): """ Extends Django's default {% load %} templatetag as a new tag called {% import %}, which allows for extended functionality (while being backwards compatible). Load a tag library from a particular app: {% import myapp:mytaglib %} Load a particular tag from a particular app: {% import mytag from myapp:mytaglib %} Load a particular tag from a particular app and rename: {% import mytag from myapp:mytaglib as othername %} **Note**: you cannot rename multiple tags, so if you do: {% import mytag myothertag from myapp:mytaglib as othername %} then only the last tag will be using othername, and the first one won't be imported. """ bits = token.contents.split() if (len(bits) >= 4 and bits[-2] == "from") or (len(bits) >= 6 and bits[-2] == "as"): lib_index = -1 as_lib = None if (bits[-2] == "as"): lib_index = -3 as_lib = bits[-1] try: taglib = bits[lib_index] lib = get_library(taglib) except InvalidTemplateLibrary as e: raise TemplateSyntaxError("'%s' is not a valid tag library: %s" % (taglib, e)) else: temp_lib = Library() for name in bits[1:(lib_index - 1)]: name_to_use = as_lib if as_lib else name if name in lib.tags: temp_lib.tags[name_to_use] = 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_to_use] = lib.filters[name] elif name in lib.filters: temp_lib.filters[name_to_use] = 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) else: for taglib in bits[1:]: # add the library to the parser try: lib = get_library(taglib) parser.add_library(lib) except InvalidTemplateLibrary as e: raise TemplateSyntaxError("'%s' is not a valid tag library: %s" % (taglib, e)) return LoadNode()
import sys import re from datetime import datetime from itertools import groupby, cycle as itertools_cycle from django.template.base import Node, NodeList, Template, Context, Variable from django.template.base import TemplateSyntaxError, VariableDoesNotExist, BLOCK_TAG_START, BLOCK_TAG_END, VARIABLE_TAG_START, VARIABLE_TAG_END, SINGLE_BRACE_START, SINGLE_BRACE_END, COMMENT_TAG_START, COMMENT_TAG_END from django.template.base import get_library, Library, InvalidTemplateLibrary from django.template.smartif import IfParser, Literal from django.template.defaultfilters import date from django.conf import settings from django.utils.encoding import smart_str, smart_unicode from django.utils.safestring import mark_safe register = Library() # Regex for token keyword arguments kwarg_re = re.compile(r"(?:(\w+)=)?(.+)") def token_kwargs(bits, parser, support_legacy=False): """ A utility method for parsing token keyword arguments. :param bits: A list containing remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments will be removed from this list. :param support_legacy: If set to true ``True``, the legacy format ``1 as foo`` will be accepted. Otherwise, only the standard ``foo=1`` format is allowed.
from itertools import izip_longest from django.template.base import Library from django.conf import settings register = Library() """ for x in x_list for x,y in xy_list for x, y in xy_list for x, y in xy_list reversed for x in x_list reversed; y in y_list for x in x_list; y in y_list reversed """ from django.template import Node, NodeList, Template, Context, Variable from django.template import TemplateSyntaxError, VariableDoesNotExist class ForNode(Node): child_nodelists = ('nodelist_loop', 'nodelist_empty') zip = zip get_overall_len = min def __init__(self, loopvars_list, sequence_list, is_reversed_list, nodelist_loop, nodelist_empty=None, zip_func=None): self.loopvars_list, self.sequence_list = loopvars_list, sequence_list self.is_reversed_list = is_reversed_list self.nodelist_loop = nodelist_loop if nodelist_empty is None: self.nodelist_empty = NodeList()
import types from django.template.base import Library from django.template.defaultfilters import stringfilter from django.utils.encoding import force_unicode from django.utils.safestring import mark_safe from biogps.utils.const import species_d register = Library() @register.filter @stringfilter def html2text(value): import html2text return html2text.html2text(value) ####################################################### #Taken from http://djangosnippets.org/snippets/1259/ # ####################################################### @register.filter def truncatesmart(value, limit=80): """ Truncates a string after a given number of chars keeping whole words. Usage: {{ string|truncatesmart }} {{ string|truncatesmart:50 }} """
from django.template.base import Library register = Library() def listStr(value): return str(value[0]) register.filter(listStr)
from django.template.base import Library, TextNode register = Library() def do_tag1(parser, token): return TextNode('<app 2 lib 2 tag 1>') def do_tag2(parser, token): return TextNode('<app 2 lib 2 tag 2>') register.tag('tag1', do_tag1) register.tag('tag2', do_tag2)
""" The file for a dynamic value template tag. Used originally in create locations. """ #pylint: disable=W0613 from django import template from django.template.base import Library register = Library() class DynamicVariableNode(template.Node): """ The Node Class for the Dynamic Value Template Tag. """ def __init__(self, form, field_string, dynamic_string): self.form = template.Variable(form) self.field_string = field_string self.dynamic_string = template.Variable(dynamic_string) def render(self, context): try: form = self.form.resolve(context) dynamic_string = self.dynamic_string.resolve(context) key = '%s%d' % (self.field_string, dynamic_string+1) return form[key] except template.VariableDoesNotExist: return '' def get_dynamic_value(parser, token): """ This is the name of the template tag to be called for a dynamic variable. """ try:
def import_taglib(parser, token): """ Extends Django's default {% load %} templatetag as a new tag called {% import %}, which allows for extended functionality (while being backwards compatible). Load a tag library from a particular app: {% import myapp:mytaglib %} Load a particular tag from a particular app: {% import mytag from myapp:mytaglib %} Load a particular tag from a particular app and rename: {% import mytag from myapp:mytaglib as othername %} **Note**: you cannot rename multiple tags, so if you do: {% import mytag myothertag from myapp:mytaglib as othername %} then only the last tag will be using othername, and the first one won't be imported. """ bits = token.contents.split() if (len(bits) >= 4 and bits[-2] == "from") or (len(bits) >= 6 and bits[-2] == "as"): lib_index = -1 as_lib = None if (bits[-2] == "as"): lib_index = -3 as_lib = bits[-1] try: taglib = bits[lib_index] lib = get_library(taglib) except InvalidTemplateLibrary as e: raise TemplateSyntaxError("'%s' is not a valid tag library: %s" % (taglib, e)) else: temp_lib = Library() for name in bits[1:(lib_index - 1)]: name_to_use = as_lib if as_lib else name if name in lib.tags: temp_lib.tags[name_to_use] = 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_to_use] = lib.filters[name] elif name in lib.filters: temp_lib.filters[name_to_use] = 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) else: for taglib in bits[1:]: # add the library to the parser try: lib = get_library(taglib) parser.add_library(lib) except InvalidTemplateLibrary as e: raise TemplateSyntaxError( "'%s' is not a valid tag library: %s" % (taglib, e)) return LoadNode()
from django.template.base import Node, NodeList, Template, Context, Variable from django.template.base import get_library, Library, InvalidTemplateLibrary from django.template.smartif import IfParser, Literal from django.conf import settings from django.utils.encoding import smart_str, smart_unicode from django.utils.safestring import mark_safe from django.template.defaulttags import url as django_url from django.utils import translation register = Library() class UrlLangNode(Node): def __init__(self, urlnode, lang): self.urlnode = urlnode self.lang = lang def render(self, context): url = self.urlnode.render(context) return '/%s%s' %( self.lang, url ) def url_lang(parser, token): url = django_url(parser, token) lang = translation.get_language()[:2] if lang != settings.LANGUAGE_CODE[:2]: urlnode = UrlLangNode(url, lang) return urlnode return url register.tag(url_lang)
from django.template.base import Variable, Library from django.conf import settings from django.utils import formats from django.utils.dateformat import format, time_format from django.utils.encoding import force_unicode, iri_to_uri from django.utils.html import (conditional_escape, escapejs, fix_ampersands, escape, urlize as urlize_impl, linebreaks, strip_tags) from django.utils.http import urlquote from django.utils.text import Truncator, wrap, phone2numeric from django.utils.safestring import mark_safe, SafeData, mark_for_escaping from django.utils.timesince import timesince, timeuntil from django.utils.translation import ugettext, ungettext from django.utils.text import normalize_newlines register = Library() ####################### # STRING DECORATOR # ####################### def stringfilter(func): """ Decorator for filters which should only receive unicode objects. The object passed as the first positional argument will be converted to a unicode object. """ def _dec(*args, **kwargs): if args: args = list(args)
#coding:utf-8 import os import logging from django.template.base import Library from django.conf import settings from django.utils.encoding import force_text from django.utils.safestring import mark_safe logger = logging.getLogger(__name__) register = Library() def static(context, link_url): """ Get the path for a static file in the Cactus build. We'll need this because paths can be rewritten with fingerprinting. """ #TODO: Support URLS that don't start with `/static/` site = context['__CACTUS_SITE__'] page = context['__CACTUS_CURRENT_PAGE__'] url = site.get_url_for_static(link_url) if url is None: # For the static method we check if we need to add a prefix helper_keys = [ "/static/" + link_url, "/static" + link_url,
"""Default tags used by the template system, available to all templates.""" import sys import re from itertools import groupby, cycle as itertools_cycle from django.template.base import Node, NodeList, Template, Context, Variable from django.template.base import TemplateSyntaxError, VariableDoesNotExist, BLOCK_TAG_START, BLOCK_TAG_END, VARIABLE_TAG_START, VARIABLE_TAG_END, SINGLE_BRACE_START, SINGLE_BRACE_END, COMMENT_TAG_START, COMMENT_TAG_END from django.template.base import get_library, Library, InvalidTemplateLibrary from django.template.smartif import IfParser, Literal from django.conf import settings from django.utils.encoding import smart_str, smart_unicode from django.utils.safestring import mark_safe register = Library() # Regex for token keyword arguments kwarg_re = re.compile(r"(?:(\w+)=)?(.+)") def token_kwargs(bits, parser, support_legacy=False): """ A utility method for parsing token keyword arguments. :param bits: A list containing remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments will be removed from this list. :param support_legacy: If set to true ``True``, the legacy format ``1 as foo`` will be accepted. Otherwise, only the standard ``foo=1`` format is allowed. :returns: A dictionary of the arguments retrieved from the ``bits`` token
#coding:utf-8 from django.template.base import Library register = Library() def current_page_name(context): """ Returns the current page name without slashes """ page = context['__CACTUS_CURRENT_PAGE__'] return page.final_url register.simple_tag(takes_context=True)(current_page_name)
from itertools import izip_longest from django.template.base import Library from django.conf import settings register = Library() """ for x in x_list for x,y in xy_list for x, y in xy_list for x, y in xy_list reversed for x in x_list reversed; y in y_list for x in x_list; y in y_list reversed """ from django.template import Node, NodeList from django.template import TemplateSyntaxError, VariableDoesNotExist class ForNode(Node): child_nodelists = ('nodelist_loop', 'nodelist_empty') zip = zip get_overall_len = min def __init__(self, loopvars_list, sequence_list, is_reversed_list, nodelist_loop, nodelist_empty=None, zip_func=None): self.loopvars_list, self.sequence_list = loopvars_list, sequence_list self.is_reversed_list = is_reversed_list self.nodelist_loop = nodelist_loop if nodelist_empty is None: self.nodelist_empty = NodeList()
# License for the specific language governing permissions and limitations # under the License. # # However, if you have executed another commercial license agreement # with Crate these terms will supersede the license and you may use the # software solely pursuant to the terms of the relevant commercial agreement. __docformat__ = "reStructuredText" import json import datetime from django.template.base import Library from django.utils.safestring import mark_safe register = Library() CDN_URL = 'https://crate.io' def media(context, media_url): """ Get the path for a media file. """ if media_url.startswith('http://') or media_url.startswith('https://'): url = media_url elif media_url.startswith('/'): url = u'{0}{1}'.format(CDN_URL, media_url) else: url = u'{0}/media/{1}'.format(CDN_URL, media_url)
# coding:utf-8 import os import logging from django.template.base import Library from django.utils.encoding import force_text from django.utils.safestring import mark_safe logger = logging.getLogger(__name__) register = Library() def static(context, link_url): """ Get the path for a static file in the Cactus build. We'll need this because paths can be rewritten with fingerprinting. """ # TODO: Support URLS that don't start with `/static/` site = context['__CACTUS_SITE__'] page = context['__CACTUS_CURRENT_PAGE__'] url = site.get_url_for_static(link_url) if url is None: # For the static method we check if we need to add a prefix helper_keys = [ "/static/" + link_url, "/static" + link_url, "static/" + link_url
def add_library(self, library): wrapped_library = Library() wrapped_library.filters = library.filters for name, tag_compiler in library.tags.items(): wrapped_library.tags[name] = self.wrap_compile_function(name, tag_compiler) self.parser.add_library(wrapped_library)
# License for the specific language governing permissions and limitations # under the License. # # However, if you have executed another commercial license agreement # with Crate these terms will supersede the license and you may use the # software solely pursuant to the terms of the relevant commercial agreement. __docformat__ = "reStructuredText" import json import datetime from django.template.base import Library from django.utils.safestring import mark_safe register = Library() CDN_URL = 'https://crate.io' def media(context, media_url): """ Get the path for a media file. """ if media_url.startswith('http://') or media_url.startswith('https://'): url = media_url elif media_url.startswith('/'): url = u'{0}{1}'.format(CDN_URL, media_url) else: url = u'{0}/media/{1}'.format(CDN_URL, media_url) return url
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.template.base import Library from classytags.helpers import InclusionTag from adminlinks.templatetags.utils import context_passes_test register = Library() class AdminlinksCssShortcut(InclusionTag): """ Helper for rendering any Stylesheets (CSS) we want to ship by default. Can include inline (inside a `<style>` tag) or external (via a `<link>` tag) styles. """ template = 'adminlinks/css.html' def get_context(self, context): """ Tests and updates the existing context. :param context: a :class:`~django.template.Context` which is checked via :meth:`~adminlinks.templatetags.utils.context_passes_test`, and the result **always** put into the context. :return: the context, possibly modified with a new layer. :rtype: :class:`~django.template.RequestContext` or other context/ dictionary-like object. """ result = context_passes_test(context) context.update({'should_load_assets': result})
# coding: utf-8 # Шаблонный тег для вывода текущего года на всех страницах сайта # чтобы можно было менять год в одном месте (в БД таблица = site_year), # а не на всех страницах сайта по отдельности. from django.db import connection from django.template.base import Library, Node register = Library() class SiteYearNode(Node): def render(self, context): last_year = connection.cursor() last_year.execute(""" SELECT sy.year FROM site_year sy WHERE sy.id = ( SELECT MAX(sy.id) FROM site_year sy ) ; """) # Запрос вернет год с максимальным айдишником, # а так как текущий год добавляется в таблицу ручками, # то и айдишник у этого года будет максимальный, # т.к. id это автоинкрементное поле year_result = last_year.fetchone() return year_result[0] def siteyear_tag(parser, token): return SiteYearNode()
from django.template.base import Library register = Library() def get(d, key): return d.get(key, '') register.filter('get', get)
from django.template.base import TemplateSyntaxError, TemplateDoesNotExist from django.template.base import Library, TextNode from django.template.loader import get_template_from_string, find_template_loader, make_origin from django.template.loader_tags import BlockContext, BlockNode, ExtendsNode, BLOCK_CONTEXT_KEY from django.conf import settings from override.settings import MAKE_OVERRIDE_TAGS_BUILT_IN register = Library() class OverrideError(Exception): pass def find_template(name, dirs=None, override_level=1): # Calculate template_source_loaders the first time the function is executed # because putting this logic in the module-level namespace may cause # circular import errors. See Django ticket #1292. from django.template.loader import template_source_loaders origin_override_level = override_level if template_source_loaders is None: loaders = [] for loader_name in settings.TEMPLATE_LOADERS: loader = find_template_loader(loader_name) if loader is not None: loaders.append(loader) template_source_loaders = tuple(loaders) for loader in template_source_loaders: try: