class Addtoblock(SekizaiTag): name = 'addtoblock' options = Options( Argument('name'), Flag('strip', default=False, true_values=['strip']), parser_class=AddtoblockParser, ) def render_tag(self, context, name, strip, nodelist): rendered_contents = nodelist.render(context) if strip: rendered_contents = rendered_contents.strip() varname = get_varname() context[varname][name].append(rendered_contents) return ""
class RenderPlugin(Tag): template = 'cms/content.html' name = 'render_plugin' options = Options(Argument('plugin')) def render_tag(self, context, plugin): if not plugin: return '' content_renderer = context['cms_content_renderer'] content = content_renderer.render_plugin( instance=plugin, context=context, editable=content_renderer.user_is_on_edit_mode(), ) return content
class ShowFeedback(Tag): name = 'show_feedback' options = Options(Argument('form_key', required=False, resolve=False)) def render_tag(self, context, form_key): form_key = form_key if form_key else DEFAULT_FORM_KEY form = get_feedback_form(form_key)() if PREFIX_KEY_FIELDS: form.prefix = form_key return render_to_string([ 'feedback/%s/feedback.html' % form_key, 'feedback/feedback.html', ], {'form': form}, context_instance=RequestContext( context['request']))
class ShowSlider(Tag): name = 'show_slider' options = Options(Argument('key', required=False, resolve=False)) def render_tag(self, context, key=None): try: if key: slides = Slider.objects.get(key=key).slides.filter(show=True) else: obj = context.get('current_page') obj_ct = ContentType.objects.get_for_model(obj) slides = Slide.objects.filter(content_type=obj_ct, object_id=obj.id, show=True) key = 'frontpage' template = 'sliders/%s/slider.html' % key return render_to_string(template, {'slides': slides}, context['request']) except ObjectDoesNotExist: return ''
class Subscribe(InclusionTag): name = 'mailchimp_subscribe_form' template = 'cmsplugin_mailchimp/subscribe.html' options = Options( Argument('list_id'), StringArgument('template', default='cmsplugin_mailchimp/subscribe.html', required=False), ) def get_context(self, context, list_id, template): subscribeForm = SubscribeForm(initial={'list_id': list_id}) return context.update({ 'csrf_token': context['csrf_token'], 'form': subscribeForm, 'template': template, })
class CMSToolbar(RenderBlock): name = 'cms_toolbar' options = Options( Argument('name', required=False), # just here so sekizai thinks this is a RenderBlock parser_class=SekizaiParser, ) def render_tag(self, context, name, nodelist): # render JS request = context.get('request', None) toolbar = getattr(request, 'toolbar', None) if toolbar: toolbar.init_toolbar(request) toolbar.populate() if request and 'cms-toolbar-login-error' in request.GET: context['cms_toolbar_login_error'] = request.GET['cms-toolbar-login-error'] == '1' context['cms_version'] = __version__ context['django_version'] = DJANGO_VERSION context['python_version'] = PYTHON_VERSION context['cms_edit_on'] = get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON') context['cms_edit_off'] = get_cms_setting('CMS_TOOLBAR_URL__EDIT_OFF') if toolbar and toolbar.show_toolbar: language = toolbar.toolbar_language with force_language(language): # needed to populate the context with sekizai content render_to_string('cms/toolbar/toolbar_javascript.html', flatten_context(context)) context['addons'] = mark_safe(toolbar.render_addons(context)) else: language = None # render everything below the tag rendered_contents = nodelist.render(context) # sanity checks if not request: return rendered_contents if not toolbar: return rendered_contents if not toolbar.show_toolbar: return rendered_contents # render the toolbar content request.toolbar.post_template_populate() with force_language(language): addons = mark_safe(toolbar.post_template_render_addons(context)) toolbar = render_to_string('cms/toolbar/toolbar.html', flatten_context(context)) # return the toolbar content and the content below return '%s\n%s\n%s' % (toolbar, addons, rendered_contents)
class PaginationCtl(InclusionTag): name = 'pagination_ctl' template = 'templatetags/pagination_ctl.html' options = Options( Argument('page', required=True, resolve=True), KeywordArgument('url', default='', required=False, resolve=True), KeywordArgument('url_args', default={}, required=False, resolve=True) ) def get_context(self, context, page, url='', url_args={}): url = url.get('url', '') page_obj = page url_params = url_args.get('url_args', {}) if 'page' in url_params: del url_params['page'] url_args = urllib.urlencode(url_params) pages = [] paginator = page_obj.paginator max_pages = 9 if paginator.num_pages < max_pages: pages = range(1, paginator.num_pages + 1) else: half = max_pages // 2 page_start = int(page_obj.number - half) if (page_start + max_pages) > paginator.num_pages: page_start = paginator.num_pages - max_pages if page_start > 0: pages = range(page_start, page_start + max_pages + 1) else: pages = range(1, max_pages + 1) return { 'page_obj': page_obj, 'url': url, 'url_params': url_args, 'page_range': pages }
class CMSToolbar(RenderBlock): name = 'cms_toolbar' options = Options( Argument('name', required=False ), # just here so sekizai thinks this is a RenderBlock parser_class=SekizaiParser, ) def render_tag(self, context, name, nodelist): # render JS request = context.get('request', None) toolbar = getattr(request, 'toolbar', None) if toolbar: toolbar.populate() if request and 'cms-toolbar-login-error' in request.GET: context['cms_toolbar_login_error'] = request.GET[ 'cms-toolbar-login-error'] == '1' context['cms_version'] = __version__ if toolbar and toolbar.show_toolbar: language = toolbar.toolbar_language with force_language(language): # needed to populate the context with sekizai content render_to_string('cms/toolbar/toolbar_javascript.html', context) clipboard = mark_safe( render_to_string('cms/toolbar/clipboard.html', context)) else: language = None clipboard = '' # render everything below the tag rendered_contents = nodelist.render(context) # sanity checks if not request: return rendered_contents if not toolbar: return rendered_contents if not toolbar.show_toolbar: return rendered_contents # render the toolbar content request.toolbar.post_template_populate() with force_language(language): context['clipboard'] = clipboard content = render_to_string('cms/toolbar/toolbar.html', context) # return the toolbar content and the content below return '%s\n%s' % (content, rendered_contents)
class RenderPlaceholderField(InclusionTag): """ Inclusion tag for static placeholder. RUS: Класс тега для статического заполнителя. """ template = 'edw_fluent/partials/_renderplaceholder.html' name = 'render_placeholder_field' options = Options(Argument('placeholder_id', resolve=True), ) def get_context(self, context, placeholder_id): """ RUS: Возвращает контекст, дополненный id заполнителя. """ placeholder_object = Placeholder.objects.get(id=placeholder_id) context.update({'placeholder_object': placeholder_object}) return context
class GetTermTree(BaseRetrieveDataTag): name = 'get_term_tree' queryset = TermModel.objects.toplevel() serializer_class = TermTreeSerializer action = 'tree' options = Options(MultiKeywordArgument('kwargs', required=False), 'as', Argument('varname', required=False, resolve=False)) def render_tag(self, context, kwargs, varname): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True, context=context) data = serializer.data if varname: context[varname] = data return '' else: return self.to_json(data)
class MainMenu(ShowMenu): name = 'main_menu' options = Options( IntegerArgument('from_level', default=0, required=False), StringArgument('template', default='cms/bootstrap3/main-menu.html', required=False), StringArgument('namespace', default=None, required=False), StringArgument('root_id', default=None, required=False), Argument('next_page', default=None, required=False), ) def get_context(self, context, from_level, template, namespace, root_id, next_page): return super(MainMenu, self).get_context(context, from_level, 1, 1, 1, template, namespace, root_id, next_page)
class SkillsTotal(MetricTotalTag): options = Options( KeywordArgument('garden', required=False), KeywordArgument('start', required=False), KeywordArgument('end', required=False), KeywordArgument('shared', required=True), 'as', Argument('varname', resolve=False, required=False), ) def get_metric_model(self): return SmartsAndSkills def get_value(self, context, garden, start, end, shared): shared = shared['shared'] kwargs = self.args_to_dict(garden, start, end) records = self.get_records(**kwargs) return records.aggregate(total=Sum(shared))['total']
class StaticPlaceholderNode(Tag): name = 'static_placeholder' options = PlaceholderOptions( Argument('code', required=True), MultiValueArgument('extra_bits', required=False, resolve=False), blocks=[ ('endstatic_placeholder', 'nodelist'), ] ) def render_tag(self, context, code, extra_bits, nodelist=None): # TODO: language override (the reason this is not implemented, is that language selection is buried way # down somewhere in some method called in render_plugins. There it gets extracted from the request # and a language in request.GET always overrides everything.) if not code: # an empty string was passed in or the variable is not available in the context if nodelist: return nodelist.render(context) return '' request = context.get('request', False) if not request: if nodelist: return nodelist.render(context) return '' if isinstance(code, StaticPlaceholder): static_placeholder = code else: if 'site' in extra_bits: site = Site.objects.get_current() static_placeholder, __ = StaticPlaceholder.objects.get_or_create(code=code, site_id=site.pk, defaults={'name': code, 'creation_method': StaticPlaceholder.CREATION_BY_TEMPLATE}) else: static_placeholder, __ = StaticPlaceholder.objects.get_or_create(code=code, site_id__isnull=True, defaults={'name': code, 'creation_method': StaticPlaceholder.CREATION_BY_TEMPLATE}) if not hasattr(request, 'static_placeholders'): request.static_placeholders = [] request.static_placeholders.append(static_placeholder) if hasattr(request, 'toolbar') and request.toolbar.edit_mode: placeholder = static_placeholder.draft else: placeholder = static_placeholder.public placeholder.is_static = True content = render_placeholder(placeholder, context, name_fallback=code, default=nodelist) return content
class FrontEditModelTag(Tag): name = 'front_edit_model' options = Options(Argument('instance', resolve=False, required=True), blocks=[ ('end_front_edit_model', 'nodelist'), ]) def render_tag(self, context, instance='', nodelist=None): obj = context.get('object', None) model_placeholder = getattr(obj, instance) hash_val = Placeholder.key_for(str(model_placeholder.id)) cache_key = "front-edit-%s" % hash_val val = cache.get(cache_key) if val is None: try: val = Placeholder.objects.get(key=hash_val).value cache.set(cache_key, val, 3600 * 24) except Placeholder.DoesNotExist: pass if val is None and nodelist: val = nodelist.render(context) classes = ['editable'] user = context.get('request', None) and context.get('request').user user_can_change = False if obj: opts = type(obj)._meta codename = get_permission_codename('change', opts) change_perm = '{}.{}'.format(opts.app_label, codename) user_can_change = user.has_perm(change_perm) if django_front_settings.DJANGO_FRONT_PERMISSION( user) or user_can_change: render = six.text_type(smart_text(val)).strip() if not strip_tags(render).strip(): classes.append('empty-editable') return '<div class="%s" id="%s">%s</div>' % (' '.join(classes), hash_val, render) return val or ''
class get_agenda(Tag): """ Fetches all sessions Usage: {% get_agenda as agenda %} {% for session in agenda %} """ options = Options('as', Argument('varname', required=False, resolve=False)) def render_tag(self, context, varname): agenda = [] for slot in Slot.objects.all(): qs = Session.objects.filter(slot=slot).order_by("room") sessions = [] if qs: for s in qs: speaker = "%s %s" % (s.speaker.first_name, s.speaker. last_name) if s.speaker else None speaker_id = s.speaker.pk if s.speaker else None sessions.append({ "speaker": speaker, "speaker_id": speaker_id, "title": s.title, "url": s.get_absolute_url(), "excerpt": s.excerpt, "room": s.room, "is_break": s.is_break }) agenda.append({ "start": slot.start, "end": slot.end, "sessions": sessions }) if varname: context[varname] = agenda return '' else: return agenda
class SkillsExamples(MetricRecordsMixin, AsTag): options = Options( KeywordArgument('garden', required=False), KeywordArgument('start', required=False), KeywordArgument('end', required=False), KeywordArgument('shared', required=True), 'as', Argument('varname', resolve=False, required=False), ) def get_metric_model(self): return SmartsAndSkills def get_value(self, context, garden, start, end, shared): shared = shared['shared'] kwargs = self.args_to_dict(garden, start, end) records = self.get_records(**kwargs).order_by('recorded') return OrderedDict([(r.recorded, getattr(r, '%s_examples' % shared)) for r in records])
class RenderMenu(InclusionTag): """ Renders children of given menu to given depth. """ name = "render_menu" template = "amenu/render_menu.html" options = Options( Argument('page', required=True), IntegerArgument('depth', required=True), ) def get_context(self, context, page, depth): if depth is not 0: context['depth'] = depth - 1 context['pages'] = page.get_children() else: context = None return context
class FrontEditTag(Tag): name = 'front_edit' options = Options( Argument('name', resolve=False, required=True), MultiValueArgument('extra_bits', required=False, resolve=True), blocks=[('end_front_edit', 'nodelist')], ) def render_tag(self, context, name, extra_bits, nodelist=None): hash_val = Placeholder.key_for(name, *extra_bits) cache_key = "front-edit-%s" % hash_val val = cache.get(cache_key) if val is None: try: val = Placeholder.objects.get(key=hash_val).value cache.set(cache_key, val, 3600 * 24) except Placeholder.DoesNotExist: pass if val is None and nodelist: val = nodelist.render(context) classes = ['editable'] if getattr(django_front_settings, 'DJANGO_FRONT_EXTRA_CONTAINER_CLASSES', None): classes.append( six.text_type(django_front_settings. DJANGO_FRONT_EXTRA_CONTAINER_CLASSES)) user = context.get('request', None) and context.get('request').user if django_front_settings.DJANGO_FRONT_PERMISSION(user): render = six.text_type(smart_text(val)).strip() if not strip_tags(render).strip(): classes.append('empty-editable') return '<div class="%s" id="%s">%s</div>' % ( ' '.join(classes), hash_val, render, ) return val or ''
class StaticPlaceholderNode(Tag): name = 'static_placeholder' options = PlaceholderOptions(Argument('code', required=True), MultiValueArgument('extra_bits', required=False, resolve=False), blocks=[ ('endstatic_placeholder', 'nodelist'), ]) def render_tag(self, context, code, extra_bits, nodelist=None): content_renderer = context.get('cms_content_renderer') if not code or not content_renderer: # an empty string was passed in or the variable is not available in the context # OR cms_content_renderer is missing from context if nodelist: return nodelist.render(context) return '' if isinstance(code, StaticPlaceholder): static_placeholder = code else: kwargs = { 'code': code, 'defaults': { 'creation_method': StaticPlaceholder.CREATION_BY_TEMPLATE } } if 'site' in extra_bits: kwargs['site'] = Site.objects.get_current() else: kwargs['site_id__isnull'] = True static_placeholder = StaticPlaceholder.objects.get_or_create( **kwargs)[0] content = content_renderer.render_static_placeholder( static_placeholder, context=context, nodelist=nodelist, ) return content
class CMSEditableObjectBlock(CMSEditableObject): """ Templatetag that links a content extracted from a generic django model to the model admin changeform. The rendered content is to be specified in the enclosed block. """ name = 'render_model_block' options = Options( Argument('instance'), Argument('edit_fields', default=None, required=False), Argument('language', default=None, required=False), Argument('view_url', default=None, required=False), Argument('view_method', default=None, required=False), 'as', Argument('varname', required=False, resolve=False), blocks=[('endrender_model_block', 'nodelist')], ) def render_tag(self, context, **kwargs): """ Renders the block and then inject the resulting HTML in the template context """ context.push() template = self.get_template(context, **kwargs) data = self.get_context(context, **kwargs) data['content'] = mark_safe(kwargs['nodelist'].render(data)) data['rendered_content'] = data['content'] output = render_to_string(template, data) context.pop() if kwargs.get('varname'): context[kwargs['varname']] = output return '' else: return output def get_context(self, context, instance, edit_fields, language, view_url, view_method, varname, nodelist): """ Uses _get_empty_context and adds the `instance` object to the local context. Context here is to be intended as the context of the nodelist in the block. """ extra_context = self._get_empty_context(context, instance, edit_fields, language, view_url, view_method) extra_context['instance'] = instance extra_context['render_model_block'] = True return extra_context
class StrideRenderer(Tag): """ Render the serialized content of a placeholder field using the full cascade of plugins. {% render_cascade "cascade-data.json" %} Keyword arguments: datafile -- Filename containing the cascade tree. Must be file locatable by Django's static file finders. """ name = 'render_cascade' options = Options( Argument('datafile'), ) def render_tag(self, context, datafile): from sekizai.helpers import get_varname as get_sekizai_context_key from cmsplugin_cascade.strides import StrideContentRenderer cache = caches['default'] tree_data_key = 'cascade-strides:' + datafile tree_data = cache.get(tree_data_key) if cache else None if tree_data is None: jsonfile = finders.find(datafile) if not jsonfile: raise IOError("Unable to find file: {}".format(datafile)) with io.open(jsonfile) as fp: tree_data = json.load(fp) content_renderer = StrideContentRenderer(context['request']) with context.push(cms_content_renderer=content_renderer): content = content_renderer.render_cascade(context, tree_data) # some templates use Sekizai's templatetag `addtoblock` or `add_data`, which have to be re-added to the context cache = caches['default'] if cache: sekizai_context_key = get_sekizai_context_key() SEKIZAI_CONTENT_HOLDER = cache.get_or_set(sekizai_context_key, context.get(sekizai_context_key)) if SEKIZAI_CONTENT_HOLDER: for name in SEKIZAI_CONTENT_HOLDER: context[sekizai_context_key][name] = SEKIZAI_CONTENT_HOLDER[name] return content
class RenderIdentifier(Tag): """ Given a CMS Placeholder page identifier, render the content of the placeholder field. """ name = 'render_identifier' options = Options( Argument('page_identifier'), ) def render_tag(self, context, page_identifier): request = context.get('request', None) if not request: return '' if not page_identifier: return '' placeholders = CMSPlaceholder.objects.filter(page_identifier=page_identifier) if not placeholders: return "" ph = placeholders[0] return safe(ph.cmscontent_placeholder.render(context, None))
class CMSToolbar(RenderBlock): name = 'cms_toolbar' options = Options( Argument('name', required=False), # just here so sekizai thinks this is a RenderBlock parser_class=SekizaiParser, ) def render_tag(self, context, name, nodelist): request = context.get('request') if not request: return nodelist.render(context) toolbar = get_toolbar_from_request(request) if toolbar and toolbar.show_toolbar: toolbar.init_toolbar(request) return toolbar.render_with_structure(context, nodelist) return nodelist.render(context)
class RenderPlugin(InclusionTag): template = 'cms/content.html' name = 'render_plugin' options = Options( Argument('plugin') ) def get_processors(self, context, plugin, placeholder): # # Prepend frontedit toolbar output if applicable. Moved to its own # method to aide subclassing the whole RenderPlugin if required. # request = context['request'] toolbar = getattr(request, 'toolbar', None) if toolbar and toolbar.edit_mode and placeholder.has_change_permission(request) and getattr(placeholder, 'is_editable', True): from cms.middleware.toolbar import toolbar_plugin_processor processors = (toolbar_plugin_processor,) else: processors = None return processors def get_context(self, context, plugin): # Prepend frontedit toolbar output if applicable if not plugin: return {'content': ''} try: placeholder = context['cms_placeholder_instance'] except KeyError: placeholder = plugin.placeholder processors = self.get_processors(context, plugin, placeholder) return { 'content': plugin.render_plugin( context, placeholder=placeholder, processors=processors ) }
class ShowMenu(InclusionTag): name = 'show_menu' template = 'workmate/menu/dummy.html' options = Options( StringArgument('template', default='workmate/menu/menu.html', required=False), StringArgument('namespace', default=None, required=False), Argument('next_page', default=None, required=False), ) def get_context(self, context, template, namespace, next_page): request = context['request'] nodes = menu_pool.get_nodes(request, namespace) nodes = check_visibility(nodes) nodes = sorted(nodes, key=lambda n: (n.menu_sort_order, n.menu_title, n.sort_order, n.title)) context['nodes'] = nodes context['template'] = template context['namespace'] = namespace return context
class Nav(Tag): ''' Render the sidebar navigation ''' name = 'nav' options = Options( Argument('hub', required=True, resolve=True), blocks=[('enter_submenu', 'item'), ('end_submenu', 'enter_submenu'), ('endnav', 'end_submenu')], ) def render_tag(self, context, hub, item, **kwargs): output = "" for x in hub.root_navigations(context['request']): context.push() context['nav_item'] = x if x.step_type in kwargs: output += kwargs[x.step_type].render(context) else: output += item.render(context) context.pop() return output
class PageLanguageUrl(InclusionTag): """ Displays the url of the current page in the defined language. You can set a language_changer function with the set_language_changer function in the utils.py if there is no page. This is needed if you have slugs in more than one language. """ name = 'page_language_url' template = 'cms/content.html' options = Options(Argument('lang'), ) def get_context(self, context, lang): try: # If there's an exception (500), default context_processors may not be called. request = context['request'] except KeyError: return {'template': 'cms/content.html'} if hasattr(request, "_language_changer"): try: setattr(request._language_changer, 'request', request) except AttributeError: pass url = "/%s" % lang + request._language_changer(lang) else: page = request.current_page if page == "dummy": return {'content': ''} try: url = page.get_absolute_url(language=lang, fallback=False) url = "/" + lang + url except: # no localized path/slug if settings.CMS_HIDE_UNTRANSLATED: # redirect to root url if CMS_HIDE_UNTRANSLATED url = '/' + lang + '/' else: # If untranslated pages are shown, this will not redirect # at all. url = '' return {'content': url}
class PluginChildClasses(InclusionTag): """ Accepts a placeholder or a plugin and renders the allowed plugins for this. """ template = "cms/toolbar/dragitem_menu.html" name = "plugin_child_classes" options = Options(Argument('obj')) def get_context(self, context, obj): # Prepend frontedit toolbar output if applicable request = context['request'] page = request.current_page child_plugin_classes = [] if isinstance(obj, CMSPlugin): slot = context['slot'] plugin = obj plugin_class = plugin.get_plugin_class() if plugin_class.allow_children: instance, plugin = plugin.get_plugin_instance() childs = [ plugin_pool.get_plugin(cls) for cls in plugin.get_child_classes(slot, page) ] # Builds the list of dictionaries containing module, name and value for the plugin dropdowns child_plugin_classes = get_toolbar_plugin_struct( childs, slot, page, parent=plugin_class) elif isinstance(obj, PlaceholderModel): placeholder = obj page = placeholder.page if placeholder else None if not page: page = getattr(request, 'current_page', None) if placeholder: slot = placeholder.slot else: slot = None # Builds the list of dictionaries containing module, name and value for the plugin dropdowns child_plugin_classes = get_toolbar_plugin_struct( plugin_pool.get_all_plugins(slot, page), slot, page) return {'plugin_classes': child_plugin_classes}
class ShowSubMenu(InclusionTag): """ show the sub menu of the current nav-node. -levels: how many levels deep -temlplate: template used to render the navigation """ name = 'show_sub_menu' template = 'menu/dummy.html' options = Options( IntegerArgument('levels', default=100, required=False), Argument('template', default='menu/sub_menu.html', required=False), ) def get_context(self, context, levels, template): try: # If there's an exception (500), default context_processors may not be called. request = context['request'] except KeyError: return {'template': 'menu/empty.html'} nodes = menu_pool.get_nodes(request) children = [] for node in nodes: if node.selected: cut_after(node, levels, []) children = node.children for child in children: child.parent = None children = menu_pool.apply_modifiers(children, request, post_cut=True) context.update({ 'children': children, 'template': template, 'from_level': 0, 'to_level': 0, 'extra_inactive': 0, 'extra_active': 0 }) return context
class CurrentCurrencyTag(Tag): name = 'get_current_currency' options = Options( 'as', Argument('varname', resolve=False, required=False), ) def render_tag(self, context, varname): code = get_currency_code(context['request']) try: currency = Currency.active.get(code=code) except Currency.DoesNotExist: try: currency = Currency.active.default() except Currency.DoesNotExist: currency = None # shit happens... if varname: context[varname] = currency return '' else: return currency