def hashtag(algo, lib=False): def inner(value): return hexd(algo, value) return filter(function(inner), doc='Returns %s hexadecimal hash of the value. %s' % \ (algo.upper(), lib and 'Requires the :mod:`hashlib` module' or ''), name=algo, test={'args':('wtf',),'result':hexd(algo, 'wtf')})
def codectag(encoding, codec=True): codec = 'b%d%s' % (encoding, codec and 'encode' or 'decode') def inner(s, *args, **kwargs): return getattr(base64, codec)(s, *args, **kwargs) inner.__name__ = codec inner.__doc__ = getattr(base64, codec).__doc__ + """ Syntax:: {%% %s [string] [options] %%} """ % codec return filter(function(inner))
def func_factory(method): try: func = getattr(math, method) except AttributeError: return def inner(arg1, arg2=None): try: return func(arg1, arg2) except TypeError: return func(arg1) inner.__name__ = method doc = func.__doc__.splitlines() if len(doc) > 1 and not doc[1]: doc = doc[2:] inner.__doc__ = '\n'.join(doc) if method.startswith('is'): return comparison(inner) return filter(function(inner))
import re from native_tags.decorators import comparison, function def matches(pattern, text): 'String comparison. True if string ``text`` matches regex ``pattern``' return re.compile(str(pattern)).match(text) matches = comparison(matches) def substitute(search, replace, text): 'Regex substitution function. Replaces regex ``search`` with ``replace`` in ``text``' return re.sub(re.compile(str(search)), replace, text) substitute = function(substitute) def search(pattern, text): 'Regex pattern search. Returns match if ``pattern`` is found in ``text``' return re.compile(str(pattern)).search(str(text)) search = function(search)
def is_not(a): return operator.is_not(a) is_not = comparison(is_not, doc=operator.is_not.__doc__) # Mathematical and bitwise operators def abs(a): return operator.abs(a) abs = function(comparison(abs), doc=operator.abs.__doc__) def add(a, b): return operator.add(a, b) add = function(add, doc=operator.add.__doc__) def and_(a, b): return operator.and_(a, b) and_ = function(comparison(and_, name='and'), doc=operator.and_.__doc__)
""" Returns the CSS from the ``HtmlFormatter``. ``cssclass`` is the name of the ``div`` css class to use Syntax:: {% highlight_style [cssclass] [formatter options] %} Example:: {% highlight_style code linenos=true %} """ if highlighter is None: return '' return HtmlFormatter(**kwargs).get_style_defs('.%s' % cssclass) highlight_style = function(highlight_style) def highlight(code, lexer, **kwargs): """ Returns highlighted code ``div`` tag from ``HtmlFormatter`` Lexer is guessed by ``lexer`` name arguments are passed into the formatter Syntax:: {% highlight [source code] [lexer name] [formatter options] %} Example:: {% highlight 'print "Hello World"' python linenos=true %} """
import datetime from datetime import date, timedelta import random def get_last_day_of_month(year, month): if (month == 12): year += 1 month = 1 else: month += 1 return date(year, month, 1) - timedelta(1) def get_users_last_accepted_events(user, count=3, template_name="events/latest_accepted_events.html"): accepted_events = Event.objects.filter(guests=user).order_by('-end_date')[0:count] return render_to_string(template_name, {"events": accepted_events}) get_users_last_accepted_events = function(get_users_last_accepted_events) def month_cal(year, month, calendar_type="invitations", current_day=None): event_list = Event.objects.filter(\ Q(status=2)&(Q(start_date__month=month) \ & Q(start_date__year=year))|(Q(end_date__month=month) \ & Q(end_date__year=year)) ) if calendar_type=="invitations": event_list = event_list.filter(type=1)\ .filter(invitations_start__lte=datetime.datetime.now(),\ invitations_deadline__gte=datetime.datetime.now()) else: event_list = event_list.filter(type=0) first_day_of_month = date(year, month, 1)
""" assert watchable and isinstance(watchable, Watchable) assert by_bit == 'by' assert user return watchable.is_watched(user) is_watched.function = True def annotate_content(context, filenode, **options): """ Usage:: {% annotate_content filenode cssclass="code-highlight" %} """ def annotate_changeset(changeset): template_name = "projector/project/repository/"\ "annotate_changeset_cell.html" context['line_changeset'] = changeset out = render_to_string(template_name, context) return out order = ['annotate', 'ls', 'code'] headers = {} try: return annotate_highlight(filenode, order=order, headers=headers, annotate_from_changeset_func=annotate_changeset, **options) except VCSError: raise Http404 annotate_content = function(annotate_content, is_safe=True, takes_context=True)
</script> """ % {'field_id': field_id, 'options': options} return script_body autocomplete_field.function = True def do_get_code_style(context): user = context.get('user', None) if user and user.is_authenticated(): style = getattr(user.get_profile(), richtemplates_settings.PROFILE_CODE_STYLE_FIELD, richtemplates_settings.DEFAULT_CODE_STYLE) else: style = richtemplates_settings.DEFAULT_CODE_STYLE return style get_code_style = function(do_get_code_style, takes_context=True, name='get_code_style') def richicon_src(icon): """ Returns link to the icon. """ src = richtemplates_settings.ICONS_URL + icon return src richicon_src.function = True def richicon(icon, **opts): """ Returns html's ``img`` tag with message icon. """ src = richicon_src(icon) tag = '<img src="%s"' % src
import re from native_tags.decorators import comparison, function def matches(pattern, text): 'String comparison. True if string ``text`` matches regex ``pattern``' return re.compile(str(pattern)).match(text) matches = comparison(matches) matches.test = {'args': ('\d', '_'), 'result': None} def substitute(search, replace, text): 'Regex substitution function. Replaces regex ``search`` with ``replace`` in ``text``' return re.sub(re.compile(str(search)), replace, text) substitute = function(substitute) substitute.test = {'args': ('w', 'f', 'wtf'), 'result': 'ftf'} def search(pattern, text): 'Regex pattern search. Returns match if ``pattern`` is found in ``text``' return re.compile(str(pattern)).search(str(text)) search = function(search) search.test = {'args': ('\d', 'asdfasdfwe'), 'result': None}
from video.models import Video from video.forms import VideoForm register = Library() @register.inclusion_tag("video_teaser.html") def show_video_teaser(video): return {"video": video} @register.inclusion_tag("video_content.html") def show_video_content(video): return {"video": video} def add_video_dialog(request, container_id, callback_function=None, content_object=None, template_name="video/add_video_dialog.html"): return render_to_string(template_name, { "callback_function": callback_function, "container_id": container_id, "video_form": VideoForm(), }, context_instance=RequestContext(request)) add_video_dialog = function(add_video_dialog) def video_selector_list(request, callback_function=None, template_name="video/video_selector_list.html"): user = request.user videos = Video.objects.filter(creator=user).order_by("-date_added") return render_to_string(template_name, { "viewed_user": user, "videos": videos, "callback_function": callback_function, }, context_instance=RequestContext(request)) video_selector_list = function(video_selector_list)
from native_tags.decorators import function, comparison, filter from datetime import datetime def dynamic(*a, **kw): return list(a) + sorted(kw.items()) dynamic = function(dynamic) def no_render(*a, **kw): return list(a) + sorted(kw.items()) no_render = function(no_render, resolve=False) def myfilter(value, arg): return value + arg myfilter = filter(myfilter, test={'args': (1, 1), 'result': 2}) def adder(x, y): return x + y adder = function(adder, name='add', test={'args': (1, 1), 'result': 2})
from calendar import HTMLCalendar from native_tags.decorators import function def calendar(format, *args, **kwargs): """ Creates a formatted ``HTMLCalendar``. Argument ``format`` can be one of ``month``, ``year``, or ``yearpage`` Keyword arguments are collected and passed into ``HTMLCalendar.formatmonth``, ``HTMLCalendar.formatyear``, and ``HTMLCalendar.formatyearpage`` Syntax:: {% calendar month [year] [month] %} {% calendar year [year] %} {% calendar yearpage [year] %} Example:: {% calendr month 2009 10 %} """ cal = HTMLCalendar(kwargs.pop("firstweekday", 0)) return getattr(cal, "format%s" % format)(*args, **kwargs) calendar = function(calendar)
import re from django import template from photos.models import Image #from photologue.utils import EXIF register = template.Library() from misc.utils import safetylevel_filter from native_tags.decorators import function, comparison, filter from django.template import RequestContext from django.template.loader import render_to_string def add_photos_dialog(request, container_id, callback_function, content_object=None, template_name="photos/photo_add_dialog.html"): return render_to_string(template_name, { "callback_function": callback_function, "container_id": container_id, }, context_instance=RequestContext(request)) add_photos_dialog = function(add_photos_dialog) @register.tag(name="print_exif") def do_print_exif(parser, token): try: tag_name, exif = token.contents.split() except ValueError: msg = '%r tag requires a single argument' % token.contents[0] raise template.TemplateSyntaxError(msg) exif = parser.compile_filter(exif) return PrintExifNode(exif) class PrintExifNode(template.Node): def __init__(self, exif):
elif len(args) == 1: # template_name num_items, template_name = None, args[0] else: raise TemplateSyntaxError("'include_feed' tag takes either two or three arguments") num_items = int(num_items) or len(feed['entries']) for i in range(num_items): pub_date = feed['entries'][i].updated_parsed published = datetime.date(pub_date[0], pub_date[1], pub_date[2]) items.append({ 'title': feed['entries'][i].title, 'summary': feed['entries'][i].summary, 'link': feed['entries'][i].link, 'date': published }) return template_name, { 'items': items, 'feed': feed } include_feed = function(include_feed, inclusion=True) def parse_feed(feed_url): """ Parses a given feed and returns the result in a given context variable. It is **highly** recommended that you use `Django's template fragment caching`_ to cache the output of this tag for a reasonable amount of time (e.g., one hour); polling a feed too often is impolite, wastes bandwidth and may lead to the feed provider banning your IP address. .. _Django's template fragment caching: http://www.djangoproject.com/documentation/cache/#template-fragment-caching Arguments should be:
"'include_feed' tag takes either two or three arguments") num_items = int(num_items) or len(feed['entries']) for i in range(num_items): pub_date = feed['entries'][i].updated_parsed published = datetime.date(pub_date[0], pub_date[1], pub_date[2]) items.append({ 'title': feed['entries'][i].title, 'summary': feed['entries'][i].summary, 'link': feed['entries'][i].link, 'date': published }) return template_name, {'items': items, 'feed': feed} include_feed = function(include_feed, inclusion=True) def parse_feed(feed_url): """ Parses a given feed and returns the result in a given context variable. It is **highly** recommended that you use `Django's template fragment caching`_ to cache the output of this tag for a reasonable amount of time (e.g., one hour); polling a feed too often is impolite, wastes bandwidth and may lead to the feed provider banning your IP address. .. _Django's template fragment caching: http://www.djangoproject.com/documentation/cache/#template-fragment-caching
### -*- coding: utf-8 -*- #################################################### import urlparse from django.utils.translation import ugettext, ugettext_lazy as _ from native_tags.decorators import function from .models import get_group, get_second_level from .utils import alphabetic_setup, term_lookup, ALPHABET_SECOND_INDEX_NAME, alphabetic_setup_second, ALPHABET_SECOND_FILTER_COUNT PARAM_NAME = 'firstletter' alphabetic_term = function(term_lookup, takes_request=True, name="get_alphabetic_term") alphabetic_setup = function(alphabetic_setup, takes_request=True) class Group: label = '' key = '' #Unique identifier letters = () def __init__(self, label, key, letters): self.label = label self.key = key self.letters = letters LETTERS = ( u'0-9', Group(u'A-Z', "eng", (
### -*- coding: utf-8 -*- #################################################### from django.conf import settings from native_tags.decorators import function from ..models import Banner def get_banner(slug, width, height, queryset=Banner.objects.all()): banner = queryset.get_or_create(slug=slug.encode('utf-8'))[0] return "banner_source.html", { 'banner': banner, 'size': "%ix%i" % (width, height), 'width': width, 'height': height, 'STATIC_URL': settings.STATIC_URL, } get_banner = function(get_banner, inclusion=True, cache=60)
from geo.forms import LocationInputForm from django.shortcuts import get_object_or_404, render_to_response from native_tags.decorators import function, comparison, filter from django.template.loader import render_to_string from geo.models import GeoAbstractModel, GeoPointTag from django.views.decorators.cache import cache_page from django.core.cache import cache from misc.utils import get_target_contenttype from django.contrib.contenttypes.models import ContentType from django.db.models import Avg, Max, Min, Count from django.contrib.auth.models import User from django.template import RequestContext def items_in_area(): return "ddddddd" items_in_area = function(items_in_area) def get_users_tracks(user): return MGPXTrack.objects.filter(creator=user).order_by("-creation_date") get_users_tracks = function(get_users_tracks) def show_users_clustermap(user, content_type=None, request=None): return render_to_string("geo/user_cluster_widget.html", { "user": user, }, context_instance=RequestContext(request)) show_users_clustermap = function(show_users_clustermap) def list_countries(template_name="geo/country_list.html"):
from native_tags.decorators import function, comparison, filter from datetime import datetime def dynamic(*a, **kw): return list(a) + sorted(kw.items()) dynamic = function(dynamic) def no_render(*a, **kw): return list(a) + sorted(kw.items()) no_render = function(no_render, resolve=False) def myfilter(value, arg): return value + arg myfilter = filter(myfilter, test={'args':(1,1),'result':2}) def adder(x, y): return x + y adder = function(adder, name='add', test={'args':(1,1),'result':2}) def cmp_kwargs(**kw): return len(kw) cmp_kwargs = comparison(cmp_kwargs) def myinc(noun): return 'unittest.html', {'noun': noun} myinc = function(myinc, inclusion=True) def ifsomething(): return True ifsomething = comparison(ifsomething)
from native_tags.decorators import function, comparison, filter from datetime import datetime def dynamic(*a, **kw): return list(a) + sorted(kw.items()) dynamic = function(dynamic) def no_render(*a, **kw): return list(a) + sorted(kw.items()) no_render = function(no_render, resolve=False) def myfilter(value, arg):# a, b, c): return value + arg myfilter = filter(myfilter) def adder(x, y): return x + y adder = function(adder, name='add') def cmp_kwargs(**kw): return len(kw) cmp_kwargs = comparison(cmp_kwargs) def myinc(noun): return 'unittest.html', {'noun': noun} myinc = function(myinc, inclusion=True) def ifsomething(): return True ifsomething = comparison(ifsomething)
from calendar import HTMLCalendar from native_tags.decorators import function def calendar(format, *args, **kwargs): """ Creates a formatted ``HTMLCalendar``. Argument ``format`` can be one of ``month``, ``year``, or ``yearpage`` Keyword arguments are collected and passed into ``HTMLCalendar.formatmonth``, ``HTMLCalendar.formatyear``, and ``HTMLCalendar.formatyearpage`` Syntax:: {% calendar month [year] [month] %} {% calendar year [year] %} {% calendar yearpage [year] %} Example:: {% calendr month 2009 10 %} """ cal = HTMLCalendar(kwargs.pop('firstweekday', 0)) return getattr(cal, 'format%s' % format)(*args, **kwargs) calendar = function(calendar)
return operator.not_(a) not_ = comparison(not_, name='not', doc=operator.not_.__doc__) def is_(a): return operator.is_(a) is_ = comparison(is_, name='is', doc=operator.is_.__doc__) def is_not(a): return operator.is_not(a) is_not = comparison(is_not, doc=operator.is_not.__doc__) # Mathematical and bitwise operators def abs(a): return operator.abs(a) abs = function(comparison(abs), doc=operator.abs.__doc__) def add(a, b): return operator.add(a, b) add = function(add, doc=operator.add.__doc__) def and_(a, b): return operator.and_(a, b) and_ = function(comparison(and_, name='and'), doc=operator.and_.__doc__) def div(a, b): return operator.div(a, b) div = function(comparison(div), doc=operator.div.__doc__) def floordiv(a, b): return operator.floordiv(a, b)
@block def officer_only(context, nodelist, user): return Compas.objects.filter(officers=user).exists() and nodelist.render(context) or '' @register.inclusion_tag('sync/sync_form.html') def sync_compas_form(compas, user): return { 'access_granted': user.is_superuser or Compas.objects.filter(pk=compas.pk, officers__pk=user.pk).exists(), 'station': compas, 'base_locked': compas.is_locked(base=True), 'update_locked': compas.is_locked(base=False), } def user_compases(user): return get_compases(user).values_list('pk', flat=True) user_compases = function(user_compases, cache=3600) @register.inclusion_tag('last_updated.html') def get_last_update(user): """dummy function, just a wrapper""" failed = False compases = get_compases(user) for c in compases: try: if c.get_last_attempt().status == ImportLogger.FAILURE: failed = True except (ImportLogger.DoesNotExist, IndexError): pass
from native_tags.decorators import function, block, filter from django.template import Template, Context def document(o): 'Returns the docstring for a given object' try: return o.__doc__ or '' except AttributeError: return '' document = filter(function(document)) def do_set(context, **kwargs): 'Updates the context with the keyword arguments' for k, v in kwargs.items(): context[k] = v return '' do_set = function(do_set, takes_context=1, name='set') def do_del(context, *args): 'Deletes template variables from the context' for name in args: del context[name] return '' do_del = function(do_del, resolve=0, takes_context=1, name='del') def render_block(context, nodelist): 'Simply renders the nodelist with the current context' return nodelist.render(context)
if (month == 12): year += 1 month = 1 else: month += 1 return date(year, month, 1) - timedelta(1) def get_users_last_accepted_events( user, count=3, template_name="events/latest_accepted_events.html"): accepted_events = Event.objects.filter( guests=user).order_by('-end_date')[0:count] return render_to_string(template_name, {"events": accepted_events}) get_users_last_accepted_events = function(get_users_last_accepted_events) def month_cal(year, month, calendar_type="invitations", current_day=None): event_list = Event.objects.filter(\ Q(status=2)&(Q(start_date__month=month) \ & Q(start_date__year=year))|(Q(end_date__month=month) \ & Q(end_date__year=year)) ) if calendar_type == "invitations": event_list = event_list.filter(type=1)\ .filter(invitations_start__lte=datetime.datetime.now(),\ invitations_deadline__gte=datetime.datetime.now()) else: event_list = event_list.filter(type=0)
For example:: {% map sha1 hello world %} calculates:: [sha1(hello), sha1(world)] """ if len(sequence) == 1: sequence = sequence[0] return map(get_func(func_name, False), sequence) do_map = function(do_map, name="map") def do_reduce(func_name, *sequence): """ Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. Functions may be registered with ``native_tags`` or can be ``builtins`` or from the ``operator`` module Syntax:: {% reduce [function] [sequence] %} {% reduce [function] [item1 item2 ...] %}
""" Retrieves the latest object from a given model, in that model's default ordering, and stores it in a context variable. The optional field argument specifies which field to get_latest_by, otherwise the model's default is used Syntax:: {% get_latest_object [app_name].[model_name] [field] as [varname] %} Example:: {% get_latest_object comments.freecomment submitted_date as latest_comment %} """ return _get_model(model)._default_manager.latest(field) get_latest_object = function(get_latest_object) def get_latest_objects(model, num, field='?'): """ Retrieves the latest ``num`` objects from a given model, in that model's default ordering, and stores them in a context variable. The optional field argument specifies which field to get_latest_by, otherwise the model's default is used Syntax:: {% get_latest_objects [app_name].[model_name] [num] [field] as [varname] %} Example:: {% get_latest_objects comments.freecomment 5 submitted_date as latest_comments %}
from django.template import Library from django.core import urlresolvers from native_tags.decorators import function, comparison, filter register = Library() import datetime import time def admin_url(app, model, action, id=None): try: if(id): return urlresolvers.reverse('admin:%s_%s_%s'%(app, model, action), args=(id,)) else: return urlresolvers.reverse('admin:%s_%s_%s'%(app, model, action)) except: return ""; admin_url = function(admin_url) def main_admin_url(): try: return urlresolvers.reverse('admin:index') except: return ""; main_admin_url = function(main_admin_url)
register = template.Library() def show_profile_preview(user): return {"user": user} register.inclusion_tag("profiles/profile_preview_horizontal.html")(show_profile_preview) def show_profile_header(viewed_user, user, title=""): return {"viewed_user": viewed_user, "user":user, "title":title} register.inclusion_tag("profiles/profile_header.html")(show_profile_header) def count_of_votes(viewed_user): from voting.models import Vote return Vote.objects.filter(user=viewed_user).count() count_of_votes = function(count_of_votes) def show_contact_select(viewed_user, element_id, callback, count=20): users = get_people_i_follow(viewed_user, count) return {"viewed_user":viewed_user, "element_id": element_id, "callback": callback, "count": count, "users": users} register.inclusion_tag("profiles/show_contact_select.html")(show_contact_select) def are_friends(user, user2): if user.is_authenticated(): are_friend = Friendship.objects.are_friends(user, user2)
autocomplete_field.function = True def do_get_code_style(context): user = context.get('user', None) if user and user.is_authenticated(): style = getattr(user.get_profile(), richtemplates_settings.PROFILE_CODE_STYLE_FIELD, richtemplates_settings.DEFAULT_CODE_STYLE) else: style = richtemplates_settings.DEFAULT_CODE_STYLE return style get_code_style = function(do_get_code_style, takes_context=True, name='get_code_style') def richicon_src(icon): """ Returns link to the icon. """ src = richtemplates_settings.ICONS_URL + icon return src richicon_src.function = True def richicon(icon, **opts):
import random as _random from native_tags.decorators import function def randrange(*args,**kwargs): if len(args)==1: args = (0,args[0]) return _random.randrange(*args,**kwargs) randrange = function(randrange) randrange.__doc__ = _random.randrange.__doc__ + """ Syntax:: {% randrange [stop] [options] %} {% randrange [start] [stop] [step] [options] %} """ def randint(a, b): return _random.randint(a, b) randint = function(randint) randint.__doc__ = _random.randint.__doc__ + """ Syntax:: {% randint [a] [b] %} """ def randchoice(*seq): if len(seq)==1: seq = seq[0] return _random.choice(seq) randchoice = function(randchoice)
def hashtag(algo, lib=False): def inner(value): return hexd(algo, value) return filter(function(inner),doc='Returns %s hexadecimal hash of the value. %s' % (algo.upper(), lib and 'Requires the :mod:`hashlib` module' or ''),name=algo)
For example:: {% map sha1 hello world %} calculates:: [sha1(hello), sha1(world)] """ if len(sequence) == 1: sequence = sequence[0] return map(get_func(func_name, False), sequence) do_map = function(do_map, name='map') do_map.test = {'args': ('ord', 'wtf'), 'result': [119, 116, 102]} def do_reduce(func_name, *sequence): """ Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. Functions may be registered with ``native_tags`` or can be ``builtins`` or from the ``operator`` module Syntax:: {% reduce [function] [sequence] %} {% reduce [function] [item1 item2 ...] %}
def annotate_content(context, filenode, **options): """ Usage:: {% annotate_content filenode cssclass="code-highlight" %} """ def annotate_changeset(changeset): template_name = "projector/project/repository/"\ "annotate_changeset_cell.html" context['line_changeset'] = changeset out = render_to_string(template_name, context) return out order = ['annotate', 'ls', 'code'] headers = {} try: return annotate_highlight( filenode, order=order, headers=headers, annotate_from_changeset_func=annotate_changeset, **options) except VCSError: raise Http404 annotate_content = function(annotate_content, is_safe=True, takes_context=True)
### -*- coding: utf-8 -*- #################################################### from native_tags.decorators import function from paypal.standard.conf import TEST from paypal_standard_ext.forms import PayPalPaymentsForm from paypal_standard_ext.utils import collect_params def paypal_shortcut(request, obj, return_url='/', cancel_url='/', form_class=PayPalPaymentsForm): if request.user.is_authenticated(): form = form_class(initial=collect_params(request, obj, return_url, cancel_url)) return form.sandbox() if TEST else form.render() else: return '' paypal_shortcut = function(paypal_shortcut, takes_request=True)
{% map [function] [item1 item2 ...] %} For example:: {% map sha1 hello world %} calculates:: [sha1(hello), sha1(world)] """ if len(sequence)==1: sequence = sequence[0] return map(get_func(func_name, False), sequence) do_map = function(do_map, name='map') do_map.test = {'args':('ord','wtf'),'result':[119, 116, 102]} def do_reduce(func_name, *sequence): """ Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. Functions may be registered with ``native_tags`` or can be ``builtins`` or from the ``operator`` module Syntax:: {% reduce [function] [sequence] %} {% reduce [function] [item1 item2 ...] %}
### -*- coding: utf-8 -*- #################################################### from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from native_tags.decorators import function from cart.cart import Cart @function def add_to_cart_url(obj, quantity): ct_pk = ContentType.objects.get_for_model(obj).pk return reverse('add_to_cart', current_app='cart', kwargs={ 'content_type_pk': ct_pk, 'object_pk': obj.pk, 'quantity': quantity }) def get_cart_count(request): return Cart(request).get_count() get_cart_count = function(get_cart_count, takes_request=1) def get_cart_amount(request): return Cart(request).cart.get_amount() get_cart_amount = function(get_cart_amount, takes_request=1)
from story.models import Story, StoryLineItemMedia from native_tags.decorators import function, comparison, filter from django.template.loader import render_to_string from django.template import RequestContext register = Library() def show_storyline(story, template_name="storyline.html"): storyline = story.storyline.order_by("position").all() return render_to_string(template_name, { "story": story, "storyline": storyline, }) show_storyline = function(show_storyline) def show_storyline_slider(story, select_callback=None, finished_callback=None, template_name="story/storyline_slider.html"): storyline = story.storyline.order_by("position").all() return render_to_string(template_name, { "story": story, "select_callback": select_callback, "finished_callback": finished_callback, }) show_storyline_slider = function(show_storyline_slider) def put_story_on_map(story, editable, template_name="story/put_story_on_map.html"): return render_to_string(template_name, { "story": story,