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 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 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, '')
"not at the expected position %s" % (tagname, token.contents)) #trim the spaces around comas, and then split the list to have all the dimensions dimensions = re.sub(r' *, *', ',', ' '.join(bits[by_index + 1:using_index])).split(',') for dim in dimensions: if not dim or ' ' in dim: raise TemplateSyntaxError("'%s' tag received an invalid argument:" " %s" % (tagname, token.contents)) #turns the cube argument into a template.Variable cube = parser.compile_filter(bits[1]) return TableFromCubeNode(cube, dimensions, bits[filepath_index]) do_tablefromcube = register.tag('tablefromcube', do_tablefromcube) class SubcubesNode(Node): def __init__(self, cube, dimensions, subcube_var, nodelist): self.dimensions, self.cube = dimensions, cube self.subcube_var = subcube_var self.nodelist = nodelist def __repr__(self): return "<Subcube Node: %s by %s as %s>" % \ (self.cube, ', '.join(self.dimensions), self.subcube_var) def __iter__(self): for node in self.nodelist: yield node
countervar, counter, extra_context = BlockTranslateParser(token.contents).top() singular = [] plural = [] while parser.tokens: token = parser.next_token() if token.token_type in (TOKEN_VAR, TOKEN_TEXT): singular.append(token) else: break if countervar and counter: if token.contents.strip() != 'plural': raise TemplateSyntaxError("'blocktrans' doesn't allow other block tags inside it") while parser.tokens: token = parser.next_token() if token.token_type in (TOKEN_VAR, TOKEN_TEXT): plural.append(token) else: break if token.contents.strip() != 'endblocktrans': raise TemplateSyntaxError("'blocktrans' doesn't allow other block tags (seen %r) inside it" % token.contents) return BlockTranslateNode(extra_context, singular, plural, countervar, counter) register.tag('get_available_languages', do_get_available_languages) register.tag('get_current_language', do_get_current_language) register.tag('get_current_language_bidi', do_get_current_language_bidi) register.tag('trans', do_translate) register.tag('blocktrans', do_block_translate)
from lizard_portal.models import PortalConfiguration register = Library() class PortalTemplate(Node): ''' give part saved as seperate template in portals map or database ''' def __init__(self, template_slug): self.template_slug = template_slug def render(self, context): slug = self.template_slug try: t = get_template('portals/'+slug+'.js') except TemplateDoesNotExist, e: pc = PortalConfiguration.objects.filter(slug=slug)[0] t = Template(pc.configuration) return t.render(context) #@register.filter def get_portal_template(parser, token): bits = token.contents.split() return PortalTemplate(bits[1]) get_portal_template = register.tag('get_portal_template', get_portal_template)
from django.template import Library, Node from math import log, pow from login_app.forms import * register = Library() import datetime class Registration_tag(Node): def render(self, context): context['registration_tag'] = RegistrationForm() return '' def get_registraion_requirement(parser, token): return Registration_tag() get_registraion_requirement_inst = register.tag(get_registraion_requirement)
{% endwith %} """ thumbnailer = get_thumbnailer(obj) thumbnailer.generate = False return thumbnailer def thumbnail_url(source, alias): """ Return the thumbnail url for a source file using an aliased set of thumbnail options. If no matching alias is found, returns an empty string. Example usage:: <img src="{{ person.photo|thumbnail_url:'small' }}" alt=""> """ try: thumb = get_thumbnailer(source)[alias] except Exception: logger.exception("Failed generating thumbnail for {0}, {1}".format(source, alias)) return '' return thumb.url register.tag(thumbnail) register.filter(thumbnailer) register.filter(thumbnailer_passive) register.filter(thumbnail_url)
self.model = get_model(*model.split('.')) def render(self, context): context[self.varname] = self.model._default_manager.all().order_by('-date_uploaded_utc')[:self.num] return '' def get_latest(parser, token): bits = token.contents.split() if len(bits) != 5: raise TemplateSyntaxError, "get_latest tag takes exactly four arguments" if bits[3] != 'as': raise TemplateSyntaxError, "third argument to get_latest tag must be 'as'" res = LatestContentNode(bits[1], bits[2], bits[4]) return res get_latest = register.tag(get_latest) @register.filter def truncatewords_by_chars(value, arg): """ Truncate words based on the number of characters based on original truncatewords filter code Receives a parameter separated by spaces where each field means: - limit: number of characters after which the string is truncated - lower bound: if char number is higher than limit, truncate by lower bound - higher bound: if char number is less than limit, truncate by higher bound """ from django.utils.text import truncate_words
if len(bits) > 2: bits = iter(bits[2:]) for bit in bits: if bit == 'as': asvar = bits.next() break else: for arg in bit.split(","): if '=' in arg: k, v = arg.split('=', 1) k = k.strip() kwargs[k] = parser.compile_filter(v) elif arg: args.append(parser.compile_filter(arg)) return URLNode(viewname, args, kwargs, asvar) url = register.tag(plus_url) @register.simple_tag def simple_url(target) : from django.core.urlresolvers import reverse, NoReverseMatch try : target = target.get_inner() except Exception, e: pass cls = target.__class__.__name__ try : if cls in ('User','Profile') : url = reverse('profile_detail', args=[target.username])
unit = '' if bytes >= 10 or ('%.1f' % bytes).endswith('.0'): bytes = '%.0f' % bytes else: bytes = '%.1f' % bytes if format.endswith('long'): unit = filesize_long_formats.get(unit, '') if base == 1024 and unit: unit = '%sbi' % unit[:2] unit = '%sbyte%s' % (unit, bytes != '1' and 's' or '') else: unit = '%s%s' % (base == 1024 and unit.upper() or unit, base == 1024 and 'iB' or 'B') return '%s %s' % (bytes, unit) if bytes == 0: return bytes base = filesize_formats.index(format[0]) + 1 # Exact multiple of 1000 if format_len == 2: return bytes / (1000.0 ** base) # Exact multiple of 1024 elif format_len == 3: bytes = bytes >> (10 * (base - 1)) return bytes / 1024.0 register.tag(thumbnail) register.filter(filesize)
</embed> </object> """ def do_youtube(parser, token): try: # split_contents() knows not to split quoted strings. 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)
def __init__(self, x): self.x = template.Variable(x) def render(self, context): context['varx'] = self.x.resolve(context) return u'' def Var(parser, token): bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError(_("Error token tag \"Var\"")) return VarNode(bits[1]) Var = register.tag(Var) #Увеличивает переменную varx в шаблоне на 1 class IncVarNode(Node): def render(self, context): if 'varx' in context: context['varx'] = int(context['varx']) + 1 return u'' def IncVar(parser, token): bits = token.split_contents() if len(bits) != 1: raise TemplateSyntaxError(_("Error token tag \"IncVar\"")) return IncVarNode()
elif mode == 'vertical': import math elements_for_columns = int( math.ceil( float(len(input)) / float(cols) ) ) start = 0 for column in range(cols): splitted[column] = input[ start : start + elements_for_columns ] start += elements_for_columns return splitted # start = 0 # for i in xrange(cols): # stop = start + len(results[i::cols]) # yield results[start:stop] # start = stop def render(self, context): context[self.new_results] = self.split_seq(context[self.results], int(self.cols), self.mode) return '' def list_to_columns(parser, token): """Parse template tag: {% list_to_colums results as new_results 2 'vertical' %}""" bits = token.contents.split() if len(bits) == 5: bits.append('vertical') if len(bits) != 6: raise TemplateSyntaxError, "list_to_columns results as new_results 2" if bits[2] != 'as': raise TemplateSyntaxError, "second argument to the list_to_columns tag must be 'as'" return SplitListNode(bits[1], bits[4], bits[3], bits[5]) list_to_columns = register.tag(list_to_columns)
if self.version_suffix: version_suffix = self.version_suffix else: try: version_suffix = self.version_suffix_var.resolve(context) except VariableDoesNotExist: return None context['version_setting'] = VERSIONS[version_suffix] return '' def version_setting(parser, token): """ Get Information about a version setting. """ try: tag, version_suffix = token.split_contents() except: raise TemplateSyntaxError("%s tag requires 1 argument" % token.contents.split()[0]) if (version_suffix[0] == version_suffix[-1] and version_suffix[0] in ('"', "'")) and version_suffix.lower()[1:-1] not in VERSIONS: raise TemplateSyntaxError("%s tag received bad version_suffix %s" % (tag, version_suffix)) return VersionSettingNode(version_suffix) register.tag(version) register.tag(version_setting)
from django.template import Library, Node from django.db.models import get_model from django.template import Variable, resolve_variable from django import template register = Library() class ObjectByPk(Node): def __init__(self, model, pk, varname): self.pk, self.varname = pk, varname self.model = get_model(*model.split('.')) def render(self, context): pk_id = resolve_variable(self.pk, context) try: context[self.varname] = self.model._default_manager.select_related().get(pk=pk_id) except self.model.DoesNotExist: context[self.varname] = None return '' def get_object_by_pk(parser, token): bits = token.contents.split() if len(bits) != 5: raise template.TemplateSyntaxError, "get_object_by_pk tag takes exactly four arguments" if bits[3] != 'as': raise template.TemplateSyntaxError, "third argument to get_object_by_pk tag must be 'as'" return ObjectByPk(bits[1], bits[2], bits[4]) get_object_by_pk = register.tag(get_object_by_pk)
except ImportError: pass try: cursor.execute('SELECT DATE_FORMAT(' + self.field + ', "%M %Y") AS date_title, DATE_FORMAT(' + self.field + ', "%Y") AS year, DATE_FORMAT(' + self.field + ', "%m") AS month,' + 'COUNT(*) as num FROM ' + self.model_table + ' GROUP BY date_title ORDER BY year DESC, month DESC') except OperationalError: raise TemplateSyntaxError('get_archives tag seems to have gotten wrong arguments. '+ 'does the table "%s" has a field "%s"?' % (self.model_table, self.field)) archives = cursor.fetchall() html_archive_links = '' for archive in archives: html_archive_links += self.htmlformat % {'nicedate': archive[0], 'year': archive[1], 'month': archive[2], 'count': archive[3], 'name': self.model._meta.verbose_name_plural} return html_archive_links def get_archives(parser, token): bits = token.split_contents() if len(bits) != 5: raise TemplateSyntaxError('get_archives tag takes exactly four arguments') if bits[3] != 'with': raise TemplateSyntaxError('third argument to get_archives tag must be "with"') return ContentArchives(bits[1], bits[2], bits[4][1:-1]+"\n\t") get_archives = register.tag(get_archives)
def __repr__(self): return "<GetLogoNode>" def render(self, context): try: logo = Logo.on_site.filter(is_active=True).latest() except Logo.DoesNotExist: logo_url = DEFAULT_LOGO_URL if not (logo_url.startswith('/') or logo_url.startswith('http://')): logo_url = "%s%s" % (settings.MEDIA_URL, logo_url) current_site = Site.objects.get_current() logo = { 'title': '[Logo %s]' % current_site.name, 'image': {'url': logo_url} } context[self.asvar] = logo return '' def get_logo(parser, token): bits = token.split_contents() if len(bits) != 3: raise TemplateSyntaxError("%r expected format is 'as name'" % bits[0]) if bits[1] != "as": raise TemplateSyntaxError("%r expected format is 'as name'" % bits[0]) asvar = bits[2] return GetLogoNode(asvar) get_logo = register.tag(get_logo)
context["content_class"] = content_class return '' def do_slots_information(parser, token): """Calculates some context variables based on displayed slots. """ bits = token.contents.split() len_bits = len(bits) if len_bits != 1: raise TemplateSyntaxError(_('%s tag needs no argument') % bits[0]) return SlotsInformationNode() register.tag('slots_information', do_slots_information) @register.inclusion_tag('lfs/mail/mail_html_footer.html', takes_context=True) def email_html_footer(context): request = context.get('request', None) shop = lfs.core.utils.get_default_shop(request) return {"shop": shop} @register.inclusion_tag('lfs/mail/mail_text_footer.html', takes_context=True) def email_text_footer(context): request = context.get('request', None) shop = lfs.core.utils.get_default_shop(request) return {"shop": shop}
def __repr__(self): return "<DbInfoNode>" def render(self, context): if not settings.TEMPLATE_DEBUG: return "" secs = 0.0 for s in db.connection.queries: secs += float(s['time']) return str("%d queries, %f seconds" % (len(db.connection.queries), secs) ) def do_dbinfo(parser, token): return DbInfoNode() do_dbinfo = register.tag('dbinfo', do_dbinfo) class DbQueryListNode(Node): def __init__(self): pass def __repr__(self): return "<DbQueryListNode>" def render(self, context): if not settings.TEMPLATE_DEBUG: return "" s = "" for q in db.connection.queries: s += "<li>" + escape(q["sql"]) + "</li>\n"
""" Provide safer CSRF Token Node """ def render(self, context): csrf_token = context.get('csrf_token', None) if csrf_token: if csrf_token == 'NOTPROVIDED': return mark_safe(u"") else: return mark_safe( u"<div style='display:none'>" "<input type='hidden' name='csrfmiddlewaretoken' " "value='%s' /></div>" % escape(csrf_token)) else: # It's very probable that the token is missing because of # misconfiguration, so we raise a warning from django.conf import settings if settings.DEBUG: import warnings warnings.warn( "A {% csrf_token %} was used in a template, " "but the context did not provide the value. " "This is usually caused by not using RequestContext.") return u'' def safe_csrf_token(parser, token): """ Safe csrf tag command """ return CsrfTokenNode() register.tag(safe_csrf_token)
from recommendations.models import Recommendation, RecAnswerLink from django.template import Library, Node register = Library() def build_tag_list(parser,token): """ {% get_tag_list %} """ return TagMenuObject() class TagMenuObject(Node): def render(self,context): output = [''] for i in Recommendation.objects.all(): number = i.post_set.count() if number >= 1: output.append(i) context["rec_tags"] = output return "" register.tag("get_tag_list",build_tag_list)
bits = tokens.split_contents() if len(bits) != 2: raise TemplateSyntaxError( "{% widget %} takes one and only one argument") field = bits.pop(1) return cls(field) @register.filter def hidden_field_errors(form): hidden_field_errors = ErrorList() for field in form.hidden_fields(): hidden_field_errors.extend(field.errors) return hidden_field_errors @register.filter def id(bound_field): widget = bound_field.field.widget for_id = widget.attrs.get('id') or bound_field.auto_id if for_id: for_id = widget.id_for_label(for_id) return for_id register.tag('formconfig', FormConfigNode.parse) register.tag('form', FormNode.parse) register.tag('formrow', FormRowNode.parse) register.tag('formfield', FormFieldNode.parse) register.tag('widget', WidgetNode.parse)
output.append(END_DIV_TEMPLATE) return "".join(output) # set up the javascript etc class ShowStarsScriptNode(Node): def render(self, context): return JS_TEMPLATE # show the stars on the template def do_show_stars(parser, token): def syntax_error(): raise TemplateSyntaxError("example: show_stars <value> of <total> round to %s [on change call <handler> with <identifier>]" % "|".join(ROUNDERS)) args = token.contents.split() if len(args) == 7: match = CMD_PATTERN.match(token.contents) elif len(args) == 13: match = EX_CMD_PATTERN.match(token.contents) else: syntax_error() if not match: syntax_error() return ShowStarsNode(*match.groups()) # put the script into the template def do_show_stars_script(parser, token): return ShowStarsScriptNode() # register the functions as filters, use aliases to the actual function names register.tag("show_stars", do_show_stars) register.tag("show_stars_script", do_show_stars_script)
"Could not detect current page.\n" "- " + str(e) + "\n" "- No context variable named 'page' found.") if not isinstance(current_page, UrlNode): raise UrlNode.DoesNotExist( "The 'page' context variable is not a valid page") prefill_parent_site(current_page) request._current_fluent_page = current_page return request._current_fluent_page # is a UrlNode def _get_request(context): """ Fetch the request from the context. This enforces the use of the template :class:`~django.template.RequestContext`, and provides meaningful errors if this is omitted. """ assert 'request' in context, "The fluent_pages_tags library requires a 'request' object in the context! Is RequestContext not used, or 'django.core.context_processors.request' not included in TEMPLATE_CONTEXT_PROCESSORS?" return context['request'] if False and __debug__: # This only exists to make PyCharm happy: # The real syntax should be passing the ``.parse`` method to the function. register.tag('render_breadcrumb', BreadcrumbNode) register.tag('render_menu', MenuNode) register.tag('get_fluent_page_vars', GetVarsNode)
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)
Extra options can be provided after an optional ``with`` argument, with each option being specified in ``[name]=[value]`` format. Valid extra options are: ``steps`` Integer. Defines the range of font sizes. ``min_count`` Integer. Defines the minimum number of times a tag must have been used to appear in the cloud. ``distribution`` One of ``linear`` or ``log``. Defines the font-size distribution algorithm to use when generating the tag cloud. Examples:: {% tag_cloud_for_entries as entries_tags %} {% tag_cloud_for_entries as entries_tags with steps=9 min_count=3 distribution=log %} """ token.contents = token.contents.replace( 'tag_cloud_for_entries', 'tag_cloud_for_model diario.Entry', 1) node = do_tag_cloud_for_model(parser, token) node.kwargs['filters'] = {'is_draft': False} return node register.tag('tag_cloud_for_entries', do_tag_cloud_for_entries)
Sample usage:: {% brand_list as var %} """ args = token.split_contents() if len(args) != 3: raise template.TemplateSyntaxError("%r tag expecting '[slug] as varname', got: %s" % (args[0], args)) var = args[2] nodelist = parser.parse(('endbrand_list',)) parser.delete_first_token() return BrandListNode(var, nodelist) register.tag('brand_list', do_brandlistnode) @register.inclusion_tag('brand_tree.html') def brand_tree(category=None): """ Creates an unordered list of the brands. Example:: <ul> <li>Books <ul> <li>Science Fiction <ul> <li>Space stories</li> <li>Robot stories</li>
def do_print_inbox_count(parser, token): """ A templatetag to show the unread-count for a logged in user. Returns the number of unread messages in the user's inbox. Usage:: {% load inbox %} {% inbox_count %} {# or assign the value to a variable: #} {% inbox_count as my_var %} {{ my_var }} """ bits = token.contents.split() if len(bits) > 1: if len(bits) != 3: raise TemplateSyntaxError, "inbox_count tag takes either no arguments or exactly two arguments" if bits[1] != 'as': raise TemplateSyntaxError, "first argument to inbox_count tag must be 'as'" return InboxOutput(bits[2]) else: return InboxOutput() register = Library() register.tag('inbox_count', do_print_inbox_count)
import urllib.parse 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 if self.asvar: context[self.asvar] = urllib.parse.urljoin(domain, context[self.asvar]) return '' else: return urllib.parse.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)
'disable_link_for_first_page': DISABLE_LINK_FOR_FIRST_PAGE, 'display_disabled_next_link': DISPLAY_DISABLED_NEXT_LINK, 'display_disabled_previous_link': DISPLAY_DISABLED_PREVIOUS_LINK, 'display_page_links': DISPLAY_PAGE_LINKS, 'is_paginated': paginator.count > paginator.per_page, 'next_link_decorator': NEXT_LINK_DECORATOR, 'page_obj': page_obj, 'page_suffix': page_suffix, 'pages': pages, 'paginator': paginator, 'previous_link_decorator': PREVIOUS_LINK_DECORATOR, 'records': records, 'request': context['request'], } if 'request' in context: getvars = context['request'].GET.copy() if 'page%s' % page_suffix in getvars: del getvars['page%s' % page_suffix] if len(getvars.keys()) > 0: new_context['getvars'] = "&%s" % getvars.urlencode() else: new_context['getvars'] = '' return new_context except (KeyError, AttributeError): return {} register = Library() register.tag('paginate', do_paginate) register.tag('autopaginate', do_autopaginate)
while parser.tokens: token = parser.next_token() if token.token_type in (TOKEN_VAR, TOKEN_TEXT): singular.append(token) else: break if countervar and counter: if token.contents.strip() != 'plural': raise TemplateSyntaxError( "'blocktrans' doesn't allow other block tags inside it") while parser.tokens: token = parser.next_token() if token.token_type in (TOKEN_VAR, TOKEN_TEXT): plural.append(token) else: break if token.contents.strip() != 'endblocktrans': raise TemplateSyntaxError( "'blocktrans' doesn't allow other block tags (seen %r) inside it" % token.contents) return BlockTranslateNode(extra_context, singular, plural, countervar, counter) register.tag('get_available_languages', do_get_available_languages) register.tag('get_current_language', do_get_current_language) register.tag('get_current_language_bidi', do_get_current_language_bidi) register.tag('trans', do_translate) register.tag('blocktrans', do_block_translate)
# Update the current session req.session['crumbs'][req.prefix] = cur # Now create HTML code to return return ''.join([i[1] for i in cur]) def __repr__(self): return "<Crumbs Node>" def do_crumbs(parser, token): return CrumbsNode() register.tag('crumbs', do_crumbs) # # A tag to update a context variable # class SetVariable(Node): def __init__(self, varname, value): self.varname = varname self.value = value def render(self, context): var = Variable(self.value).resolve(context) if var: context[self.varname] = var
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)
return bits[bits.index(key) + 1] except ValueError: return if_none bits = token.contents.split() args = { 'slug': next_bit_for(bits, 'gblock'), 'modelname': next_bit_for(bits, 'for'), 'template_path': next_bit_for(bits, 'with'), 'variable_name': next_bit_for(bits, 'as'), 'store_in_object': next_bit_for(bits, 'into'), } return GenericFlatblockNode(**args) register.tag('gblock', do_genericflatblock) ###################################################################### ##################### LIST ########################################### ###################################################################### from django.contrib.contenttypes.models import ContentType class GenericFlatblockListNode(GenericFlatblockBaseNode): def get_content_object(self, related_model, slug): # If the user passed a Integer as a slug, assume that we should fetch # this specific object try: generic_object = GenericFlatblockList._default_manager.get( slug=slug)
return "" except Exception as e: return str(e) return "" @register.tag def do_fallow(parser,token): try: # split_contents() knows not to split quoted strings. tag_name, format_string = token.split_contents() except: pass return getfallow(format_string) register.tag('fallow', do_fallow) class getelm(template.Node): def render(self, context): #print context request = context['request'] ip = request.META['REMOTE_ADDR'] return controlIPL(ip) @register.tag def do_country(parser,token): try:
try: resultant = eval(expression, variable_context) except: resultant = False if not resultant: return self.nodelist_false.render(context) return self.nodelist_true.render(context) def do_if(parser, token): bits = token.contents.split(None, 1) if len(bits) != 2: raise TemplateSyntaxError, "'if' statement requires at least one argument" expression = bits[1] variables = set([ parser.compile_filter(x) for x in variable_re.findall(expression) if x not in ('and', 'or', 'not', 'in') and not string_re.match(x) ]) nodelist_true = parser.parse(('else', 'endif')) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse(('endif', )) parser.delete_first_token() else: nodelist_false = NodeList() return IfNode(expression, variables, nodelist_true, nodelist_false) do_if = register.tag(TAGNAME, do_if)
countervar, counter, extra_context = BlockTranslateParser(token.contents).top() singular = [] plural = [] while parser.tokens: token = parser.next_token() if token.token_type in (TOKEN_VAR, TOKEN_TEXT): singular.append(token) else: break if countervar and counter: if token.contents.strip() != "plural": raise TemplateSyntaxError, "'blocktrans' doesn't allow other block tags inside it" while parser.tokens: token = parser.next_token() if token.token_type in (TOKEN_VAR, TOKEN_TEXT): plural.append(token) else: break if token.contents.strip() != "endblocktrans": raise TemplateSyntaxError, "'blocktrans' doesn't allow other block tags (seen %r) inside it" % token.contents return BlockTranslateNode(extra_context, singular, plural, countervar, counter) register.tag("get_available_languages", do_get_available_languages) register.tag("get_current_language", do_get_current_language) register.tag("get_current_language_bidi", do_get_current_language_bidi) register.tag("trans", do_translate) register.tag("blocktrans", do_block_translate)
def render(self, context): style = 'text' if len(self.vlist) > 0: style = resolve_variable(self.vlist[0], context) return highlight(self.nodelist.render(context), get_lexer_by_name(style, encoding='UTF-8'), HtmlFormatter(cssclass="pygment_highlight")) def stylize(parser, token): nodelist = parser.parse(('endstylize', )) parser.delete_first_token() return StylizeNode(nodelist, *token.contents.split()[1:]) stylize = register.tag(stylize) ########NEW FILE######## __FILENAME__ = urls from django.conf.urls.defaults import * urlpatterns = [] urlpatterns += patterns( 'django_git.views', url(r'^(?P<repo>[\w_-]+)/commit/(?P<commit>[\w\d]+)/blob/$', 'blob', name='django-git-blob'), url(r'^(?P<repo>[\w_-]+)/commit/(?P<commit>[\w\d]+)/$', 'commit', name='django-git-commit'),
register = Library() class TypeListNode(Node): def render(self, context): context['type_list'] = Type.objects.all() return '' def build_type_list(parser, token): """ {% get_type_list %} """ return TypeListNode() register.tag('get_type_list', build_type_list) class StatusListNode(Node): def __init__(self, list_type): self.list_type = Variable(list_type) def render(self, context): list_type = self.list_type.resolve(context) status_list = Status.objects.all() if list_type in ['open', 'closed']: status = list_type # values are same. status_list = status_list.filter(status=status) context['status_list'] = status_list
context[var_name] = [ i for i in group_by(obj_list, max_count_in_column) ] return '' def regroup_iter(parser, token): ''' {% regroup_iter <list> by <max_rows_count> as <save_in_variable> %} ''' bits = token.contents.split(' ') if len(bits) != 6: raise TemplateSyntaxError("tag takes six arguments") target = parser.compile_filter(bits[1]) if bits[2] != 'by': raise TemplateSyntaxError("second argument to this tag must be 'by'") max_count_in_column = parser.compile_filter(bits[3]) if bits[4] != 'as': raise TemplateSyntaxError("fours argument to this tag must be 'as'") var_name = bits[5] return RegroupIterNode(target, max_count_in_column, var_name) regroup_iter = register.tag(regroup_iter)
def do_cache(parser, token): """ This will cache the contents of a template fragment for a given amount of time. Usage:: {% load cache %} {% cache [expire_time] [fragment_name] %} .. some expensive processing .. {% endcache %} This tag also supports varying by a list of arguments:: {% load cache %} {% cache [expire_time] [fragment_name] [var1] [var2] .. %} .. some expensive processing .. {% endcache %} Each unique set of arguments will result in a unique cache entry. """ nodelist = parser.parse(('endcache',)) parser.delete_first_token() tokens = token.contents.split() if len(tokens) < 3: raise TemplateSyntaxError(u"'%r' tag requires at least 2 arguments." % tokens[0]) return CacheNode(nodelist, tokens[1], tokens[2], tokens[3:]) register.tag('cache', do_cache)
t = context.template.engine.get_template( "search/search-result.html") context.update({ "result": result, var_name: result_object, }) return t.render(context=context) except: if settings.TEMPLATE_DEBUG: raise return '' def search_result(parser, token): """ Loads the search-result.html and renders it with the current context and the given app name. {% search_result app %} """ bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError( _("%(bit)r tag takes one argument: the search result object" % {'bit': bits[0]})) return SearchResultNode(bits[1]) register.tag('search_result', search_result)
How to use it: {% pyif i == 1 or (5 >= i and i != 7) and user.first_name in ('John', 'Jacob') %} {% else %} {% endif %} """ bits = token.contents.split(None, 1) if len(bits) != 2: raise TemplateSyntaxError, "'%' statement requires at least one argument" % TAGNAME expression = bits[1] variables = set( [ parser.compile_filter(x) for x in variable_re.findall(expression) if x not in ("and", "or", "not", "in") and not string_re.match(x) ] ) nodelist_true = parser.parse(("else", "endif")) token = parser.next_token() if token.contents == "else": nodelist_false = parser.parse(("endif",)) parser.delete_first_token() else: nodelist_false = NodeList() return IfNode(expression, variables, nodelist_true, nodelist_false) do_if = register.tag(TAGNAME, do_if)
Force autoescape behaviour for this block. """ args = token.contents.split() if len(args) != 2: raise TemplateSyntaxError( "'autoescape' tag requires exactly one argument.") arg = args[1] if arg not in (u'on', u'off'): raise TemplateSyntaxError( "'autoescape' argument should be 'on' or 'off'") nodelist = parser.parse(('endautoescape', )) parser.delete_first_token() return AutoEscapeControlNode((arg == 'on'), nodelist) autoescape = register.tag(autoescape) #@register.tag def comment(parser, token): """ Ignores everything between ``{% comment %}`` and ``{% endcomment %}``. """ parser.skip_past('endcomment') return CommentNode() comment = register.tag(comment) #@register.tag
""" template based extends """ bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError, "'%s' takes one argument" % bits[0] parent_name, parent_name_expr = None, None if bits[1][0] in ('"', "'") and bits[1][-1] == bits[1][0]: parent_name = bits[1][1:-1] else: parent_name_expr = parser.compile_filter(bits[1]) nodelist = parser.parse() if nodelist.get_nodes_by_type(ExtendsNode): raise TemplateSyntaxError,"'%s' cannot appear more than once in the same template" % bits[0] return ThemeExtendsNode(nodelist,parent_name,parent_name_expr) register.tag('theme_extends',do_theme_extends) def get_theme_name(): """ 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 """
target_var = 'link' def process(self, link_id, **options): blog = self.context.get('blog') if not blog: return None qs = self.get_queryset() qs = qs.filter(blog_id=blog.pk) if options.get('category'): qs = qs.prefetch_related('category') return self.get_object(qs, link_id) register.tag('get_link', GetLinkTag.as_tag()) ## {% get_link_category category_slug **options[ as variable_name] %} ########## class GetLinkCategoryTag(SingleObjectMixin, AssignTag): field_name = 'slug' model = LinkCategory target_var = 'link_category' def process(self, category_slug, **options): blog = self.context.get('blog') if not blog: return None
cache_key = resolve_variable(self.cache_key, context) value = cache.get(cache_key) if value is None: value = self.nodelist.render(context) cache.set(cache_key, value, expire_time) return value def do_cache(parser, token): """ This will cache the contents of a template fragment for a given amount of time. Usage:: This tag also supports varying by a list of arguments:: {% load cache %} {% cache [expire_time] [variable] .. %} .. some expensive processing .. {% endcache %} Each unique set of arguments will result in a unique cache entry. """ nodelist = parser.parse(('endsimplecache',)) parser.delete_first_token() tokens = token.contents.split() if len(tokens) < 3: raise TemplateSyntaxError(u"'%r' tag requires at least 2 arguments." % tokens[0]) return CacheNode(nodelist, tokens[1], tokens[2]) register.tag('simplecache', do_cache)
from classytags.core import Options from classytags.core import Tag as TemplateTag from classytags.arguments import Argument from classytags.exceptions import ArgumentRequiredError from ..bitly import Bitly class BitlifyTag(TemplateTag): name = 'bitlify_url' """ example: {% bitlify_url 'http://www.google.it/' as bitlified_url %} """ options = Options( Argument('value', required=True, resolve=True), 'as', Argument('varname', required=False, resolve=False), ) def render_tag(self, context, value, varname): bitlified_url = Bitly().shorten_url(value) if varname: context.update({ varname: bitlified_url, }) return '' return bitlified_url register.tag(BitlifyTag) except ImportError: logger.debug("classytags is required if you want to use bitlify_url")
def render(self, context): if self.version_suffix: version_suffix = self.version_suffix else: try: version_suffix = self.version_suffix_var.resolve(context) except VariableDoesNotExist: return None context['version_setting'] = VERSIONS[version_suffix] return '' def version_setting(parser, token): """ Get Information about a version setting. """ try: tag, version_suffix = token.split_contents() except: raise TemplateSyntaxError("%s tag requires 1 argument" % token.contents.split()[0]) if (version_suffix[0] == version_suffix[-1] and version_suffix[0] in ('"', "'")) and version_suffix.lower()[1:-1] not in VERSIONS: raise TemplateSyntaxError("%s tag received bad version_suffix %s" % (tag, version_suffix)) return VersionSettingNode(version_suffix) register.tag(version) register.tag(version_object) register.tag(version_setting)
version_prefix = self.version_prefix else: try: version_prefix = self.version_prefix_var.resolve(context) except VariableDoesNotExist: return None context['version_setting'] = VERSIONS[version_prefix] return '' def version_setting(parser, token): """ Get Information about a version setting. """ try: tag, version_prefix = token.split_contents() except: raise TemplateSyntaxError, "%s tag requires 1 argument" % token.contents.split( )[0] if (version_prefix[0] == version_prefix[-1] and version_prefix[0] in ('"', "'")) and version_prefix.lower()[1:-1] not in VERSIONS: raise TemplateSyntaxError, "%s tag received bad version_prefix %s" % ( tag, version_prefix) return VersionSettingNode(version_prefix) register.tag(version) register.tag(version_object) register.tag(version_setting)
# -*- 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)
else: parent_name_expr = parser.compile_filter(bits[1]) nodelist = parser.parse() if nodelist.get_nodes_by_type(ExtendsNode): raise TemplateSyntaxError, "'%s' cannot appear more than once in the same template" % bits[ 0] return ExtendsNode(nodelist, parent_name, parent_name_expr) def do_include(parser, token): """ Loads a template and renders it with the current context. Example:: {% include "foo/some_include" %} """ bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError, "%r tag takes one argument: the name of the template to be included" % bits[ 0] path = bits[1] if path[0] in ('"', "'") and path[-1] == path[0]: return ConstantIncludeNode(path[1:-1]) return IncludeNode(bits[1]) register.tag('block', do_block) register.tag('extends', do_extends) register.tag('include', do_include)
{% endrange %} """ bits = token.split_contents() if len(bits) != 4 or bits[2] != 'as': raise TemplateSyntaxError( "%r expected format is '[start:][step:]end as name'" % bits[0] ) var_name = bits[3] rangebits = bits[1].split(':') if len(rangebits) == 1: start = 0 end = rangebits[0] step = 1 elif len(rangebits) == 2: start = rangebits[0] end = rangebits[1] step = 1 elif len(rangebits) == 3: start = rangebits[0] step = rangebits[1] end = rangebits[2] nodelist = parser.parse(('endrange',)) parser.delete_first_token() return RangeNode(var_name, start, end, step, nodelist) do_range = register.tag('range', do_range)
@register.simple_tag(takes_context=True) def show_comments(context): blog_page = context['blog_page'] entry = context['self'] if blog_page.display_comments and blog_page.disqus_shortname: ctx = { 'disqus_shortname': blog_page.disqus_shortname, 'disqus_identifier': entry.id } return render_to_string('puput/comments/disqus.html', context=ctx) return "" # Avoid to import endless_pagination in installed_apps and in the templates register.tag('show_paginator', show_pages) register.tag('paginate', paginate) @register.simple_tag(takes_context=True) def post_to_linkendin_url(context, obj_or_url=None): request = context.get('request') if request: url = _build_url(request, obj_or_url) context[ 'linkendin_url'] = 'https://www.linkedin.com/shareArticle?url={}'.format( urlencode(url)) return context @register.inclusion_tag('puput/tags/post_to_linkedin.html', takes_context=True)
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" % token.contents.split()[0]) return UUIDNode(var_name) do_uuid = register.tag('uuid', do_uuid)
param = param.strip() value = value.strip() if param in parameters: if value[0] == "\"": value = value[1:-1] parameters[param] = value return GMapNode(parameters, nodelist) class GMapScriptNode(template.Node): def __init__(self): pass def render(self, context): return INCLUDE_TEMPLATE def do_gmap_script(parser, token): try: tag_name = token.split_contents() except ValueError: raise template.TemplateSyntaxError( "La etiqueta no requiere argumentos" % token.contents[0]) return GMapScriptNode() register.tag('gmap', do_gmap) register.tag('gmap-script', do_gmap_script)
# -*- 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) """
def render(self,context): for n,arg in enumerate(self.args): if arg in context: self.args[n] = resolve_variable(arg, context) elif arg[0] == '"' and arg[-1] == '"': self.args[n] = arg[1:-1] elif arg[0] == "'" and arg[-1] == "'": self.args[n] = arg[1:-1] return self.post_render(context) def post_render(self, context): return self.args def attribute(parser, token): return GenericNode(token.split_contents()) for tag in GChartWrapper.constants.TTAGSATTRS: register.tag(tag, attribute) class ChartNode(Node): def __init__(self, tokens, nodelist): self.type = None self.tokens = [] self.mode = None if tokens and len(tokens)>1: self.type = tokens[1] if tokens[-2] == 'as': self.mode = tokens[-1] self.tokens = tokens[2:-2] else: self.tokens = tokens[2:] self.nodelist = nodelist def render(self, context):