def render_placeholder_toolbar(placeholder, context, name_fallback, save_language): from cms.plugin_pool import plugin_pool request = context['request'] page = placeholder.page if placeholder else None if not page: page = getattr(request, 'current_page', None) if page: if name_fallback and not placeholder: placeholder = Placeholder.objects.create(slot=name_fallback) page.placeholders.add(placeholder) placeholder.page = page if placeholder: slot = placeholder.slot else: slot = None context.push() all_plugins = plugin_pool.get_all_plugins() plugin_types = [cls.__name__ for cls in plugin_pool.get_all_plugins(slot, page)] context['allowed_plugins'] = plugin_types + plugin_pool.get_system_plugins() context['plugin_menu'] = get_toolbar_plugin_struct(all_plugins, slot=slot, page=page) context['placeholder'] = placeholder context['language'] = save_language context['page'] = page toolbar = render_to_string("cms/toolbar/placeholder.html", flatten_context(context)) context.pop() return toolbar
def render_plugin(context, instance, placeholder, template, processors=None, current_app=None): """ Renders a single plugin and applies the post processors to it's rendered content. """ request = context.get('request') if request: toolbar = getattr(request, 'toolbar', None) if current_app: request.current_app = current_app else: toolbar = None if toolbar and isinstance(template, six.string_types): template = toolbar.get_cached_template(template) if not processors: processors = [] if isinstance(template, six.string_types): content = render_to_string(template, flatten_context(context)) elif (isinstance(template, Template) or (hasattr(template, 'template') and hasattr(template, 'render') and isinstance(template.template, Template))): content = template.render(context) else: content = '' for processor in iterload_objects(get_cms_setting('PLUGIN_PROCESSORS')): content = processor(instance, placeholder, content, context) for processor in processors: content = processor(instance, placeholder, content, context) for processor in DEFAULT_PLUGIN_PROCESSORS: content = processor(instance, placeholder, content, context) return content
def render_placeholder_toolbar(placeholder, context, name_fallback, save_language): from cms.plugin_pool import plugin_pool request = context["request"] page = placeholder.page if placeholder else None if not page: page = getattr(request, "current_page", None) if page: if name_fallback and not placeholder: placeholder = Placeholder.objects.create(slot=name_fallback) page.placeholders.add(placeholder) placeholder.page = page if placeholder: slot = placeholder.slot else: slot = None context.push() # to restrict child-only plugins from draggables.. context["allowed_plugins"] = [ cls.__name__ for cls in plugin_pool.get_all_plugins(slot, page) ] + plugin_pool.get_system_plugins() context["placeholder"] = placeholder context["language"] = save_language context["page"] = page toolbar = render_to_string("cms/toolbar/placeholder.html", flatten_context(context)) context.pop() return toolbar
def toolbar_plugin_processor(instance, placeholder, rendered_content, original_context): from cms.plugin_pool import plugin_pool original_context.push() child_plugin_classes = [] plugin_class = instance.get_plugin_class() if plugin_class.allow_children: inst, plugin = instance.get_plugin_instance() page = original_context['request'].current_page plugin.cms_plugin_instance = inst children = [plugin_pool.get_plugin(cls) for cls in plugin.get_child_classes(placeholder, page)] # Builds the list of dictionaries containing module, name and value for the plugin dropdowns child_plugin_classes = get_toolbar_plugin_struct(children, placeholder.slot, placeholder.page, parent=plugin_class) instance.placeholder = placeholder request = original_context['request'] with force_language(request.toolbar.toolbar_language): data = { 'instance': instance, 'rendered_content': rendered_content, 'child_plugin_classes': child_plugin_classes, } # TODO: Remove js_compat once get_action_urls is refactored. data.update(instance.get_action_urls(js_compat=False)) original_context.update(data) plugin_class = instance.get_plugin_class() template = plugin_class.frontend_edit_template output = render_to_string(template, flatten_context(original_context)).strip() original_context.pop() return output
def test_flatten_context(self): context = Context({"foo": "bar"}) context.push() context.update({"bar": "baz"}) context.push() context.update({"foo": "test"}) flat = utils.flatten_context(context) expected = {"foo": "test", "bar": "baz"} if DJANGO_1_5_OR_HIGHER: expected.update({"None": None, "True": True, "False": False}) self.assertEqual(flat, expected) context.flatten = None flat = utils.flatten_context(context) self.assertEqual(flat, expected) flat = utils.flatten_context({"foo": "test", "bar": "baz"}) self.assertEqual(flat, {"foo": "test", "bar": "baz"})
def render_tag(self, context, **kwargs): """ INTERNAL! Gets the context and data to render. """ template = self.get_template(context, **kwargs) if self.push_context: safe_context = flatten_context(context) data = self.get_context(safe_context, **kwargs) safe_context.update(**data) output = render_to_string(template, safe_context) else: new_context = context.new( flatten_context(self.get_context(context, **kwargs)) ) data = flatten_context(new_context) output = render_to_string(template, data) return output
def __init__(self, dict_, instance, placeholder, processors=None, current_app=None): dict_ = flatten_context(dict_) super(PluginContext, self).__init__(dict_) if not processors: processors = [] for processor in DEFAULT_PLUGIN_CONTEXT_PROCESSORS: self.update(processor(instance, placeholder, self)) for processor in iterload_objects(get_cms_setting('PLUGIN_CONTEXT_PROCESSORS')): self.update(processor(instance, placeholder, self)) for processor in processors: self.update(processor(instance, placeholder, self))
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)
def render_tag(self, context, **kwargs): """ Overridden from InclusionTag to push / pop context to avoid leaks """ context.push() template = self.get_template(context, **kwargs) data = self.get_context(context, **kwargs) output = render_to_string(template, flatten_context(data)).strip() context.pop() if kwargs.get('varname'): context[kwargs['varname']] = output return '' else: return output
def render_plugin(self, instance, context, placeholder=None, editable=False): if not placeholder: placeholder = instance.placeholder instance, plugin = instance.get_plugin_instance() if not instance or not plugin.render_plugin: return '' # we'd better pass a flat dict to template.render # as plugin.render can return pretty much any kind of context / dictionary # we'd better flatten it and force to a Context object # flattening the context means that template must be an engine-specific template object # which is guaranteed by get_cached_template if the template returned by # plugin._get_render_template is either a string or an engine-specific template object context = PluginContext(context, instance, placeholder) context = plugin.render(context, instance, placeholder.slot) context = flatten_context(context) template = plugin._get_render_template(context, instance, placeholder) template = self.get_cached_template(template) content = template.render(context) for processor in iterload_objects( get_cms_setting('PLUGIN_PROCESSORS')): content = processor(instance, placeholder, content, context) if editable: content = self.render_editable_plugin( instance, context=context, plugin_class=plugin, placeholder=placeholder, content=content, ) placeholder_cache = self._rendered_plugins_by_placeholder[ placeholder.pk] plugins_cache = placeholder_cache.setdefault('plugins', []) plugins_cache.append(instance) for processor in DEFAULT_PLUGIN_PROCESSORS: content = processor(instance, placeholder, content, context) return content
def render_cascade(self, context, tree_data): contents = [] # create temporary copy of context to prevent pollution for other CMS placeholders context = make_context(flatten_context(context)) for plugin_type, data, children_data in tree_data.get('plugins', []): plugin_class = strides_plugin_map.get(plugin_type) element_class = strides_element_map.get(plugin_type) plugin_instance = element_class(plugin_class(), data, children_data) # create a temporary object to store the plugins cache status cms_cachable_plugins = type(str('CachablePlugins'), (object, ), {'value': True}) context.push(cms_cachable_plugins=cms_cachable_plugins) contents.append(self.render_plugin(plugin_instance, context)) return mark_safe(''.join(contents))
def render_tag(self, context, **kwargs): """ INTERNAL! Gets the context and data to render. """ template = self.get_template(context, **kwargs) if self.push_context: safe_context = flatten_context(context) data = self.get_context(safe_context, **kwargs) safe_context.update(**data) output = render_to_string(template, safe_context) else: data = context.new(self.get_context(context, **kwargs)) output = render_to_string(template, data) return output
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'] = kwargs['nodelist'].render(data) data['rendered_content'] = data['content'] output = render_to_string(template, flatten_context(data)) context.pop() if kwargs.get('varname'): context[kwargs['varname']] = output return '' else: return output
def __init__(self, dict_, instance, placeholder, processors=None, current_app=None): dict_ = flatten_context(dict_) super().__init__(dict_) if not processors: processors = [] for path in get_cms_setting('PLUGIN_CONTEXT_PROCESSORS'): processor = import_string(path) self.update(processor(instance, placeholder, self)) for processor in processors: self.update(processor(instance, placeholder, self))
def __init__(self, dict_, instance, placeholder, processors=None, current_app=None): dict_ = flatten_context(dict_) super(PluginContext, self).__init__(dict_) if not processors: processors = [] for processor in DEFAULT_PLUGIN_CONTEXT_PROCESSORS: self.update(processor(instance, placeholder, self)) for processor in iterload_objects( get_cms_setting('PLUGIN_CONTEXT_PROCESSORS')): self.update(processor(instance, placeholder, self)) for processor in processors: self.update(processor(instance, placeholder, self))
def unfave_button(context, target): user = context['request'].user # do nothing when user isn't authenticated if not user.is_authenticated(): return '' if Favorite.objects.get_favorite(user, target) is None: return '' target_model = '.'.join((target._meta.app_label, target._meta.object_name)) context = flatten_context(context) context.update({ 'target_model': target_model, 'target_object_id': target.id, }) return render_to_string('favit/unfave-button.html', context)
def render_plugin(self, instance, context, placeholder=None, editable=False): if app_settings.CMSPLUGIN_CASCADE['cache_strides'] and getattr(instance.plugin, 'cache', not editable): cache = caches['default'] key = 'cascade_element-{}'.format(instance.pk) content = cache.get(key) if content: return content else: context['cms_cachable_plugins'].value = False context = instance.plugin.render(context, instance, placeholder) context = flatten_context(context) template = instance.plugin._get_render_template(context, instance, placeholder) template = self.get_cached_template(template) content = template.render(context) if context['cms_cachable_plugins'].value: cache.set(key, content) return content
def _render(self, instance): context = SekizaiContext() context['request'] = self.request try: # django CMS 3.4+ from cms.plugin_rendering import ContentRenderer renderer = ContentRenderer(self.request) context['cms_content_renderer'] = renderer rendered = renderer.render_placeholder( instance, context, language=self.language, editable=False ) except ImportError: # django CMS 3.3 and below from cms.plugin_rendering import render_placeholder rendered = render_placeholder( instance, context, lang=self.language, editable=False ) flat = flatten_context(context) return rendered.strip(), flat
def render_plugin(self, instance, context, placeholder=None, editable=False): if getattr(instance, 'cache', not editable): cache = caches['default'] key = 'cascade_element-{}'.format(instance.pk) content = cache.get(key) if content: return content else: cache = None context = instance.plugin.render(context, instance, placeholder) context = flatten_context(context) template = instance.plugin._get_render_template(context, instance, placeholder) template = self.get_cached_template(template) content = template.render(context) if cache: cache.set(key, content) return content
def render_plugin(self, instance, context, placeholder=None, editable=False): if not placeholder: placeholder = instance.placeholder instance, plugin = instance.get_plugin_instance() if not instance or not plugin.render_plugin: return '' # we'd better pass a flat dict to template.render # as plugin.render can return pretty much any kind of context / dictionary # we'd better flatten it and force to a Context object # flattening the context means that template must be an engine-specific template object # which is guaranteed by get_cached_template if the template returned by # plugin._get_render_template is either a string or an engine-specific template object context = PluginContext(context, instance, placeholder) context = plugin.render(context, instance, placeholder.slot) context = flatten_context(context) template = plugin._get_render_template(context, instance, placeholder) template = self.get_cached_template(template) content = template.render(context) for processor in iterload_objects(get_cms_setting('PLUGIN_PROCESSORS')): content = processor(instance, placeholder, content, context) if editable: content = self.render_editable_plugin( instance, context=context, plugin_class=plugin, placeholder=placeholder, content=content, ) placeholder_cache = self._rendered_plugins_by_placeholder[placeholder.pk] plugins_cache = placeholder_cache.setdefault('plugins', []) plugins_cache.append(instance) for processor in DEFAULT_PLUGIN_PROCESSORS: content = processor(instance, placeholder, content, context) return content
def _render_cms_plugin(plugin, context): context = flatten_context(context) context['plugin'] = plugin # This my fellow ckeditor enthusiasts is a hack.. # If I let djangoCMS render the plugin using {% render_plugin %} # it will wrap the output in the toolbar markup which we don't want. # If I render the plugin without rendering a template first, then context processors # are not called and so plugins that rely on these like those using sekizai will error out. # The compromise is to render a template so that Django binds the context to it # and thus calls context processors AND render the plugin manually with the context # after it's been bound to a template. response = render_to_string( 'cms/plugins/render_plugin_preview.html', context, request=context['request'], ) return response
def _render(self, instance): context = SekizaiContext() context['request'] = self.request try: # django CMS 3.4+ from cms.plugin_rendering import ContentRenderer renderer = ContentRenderer(self.request) context['cms_content_renderer'] = renderer rendered = renderer.render_placeholder(instance, context, language=self.language, editable=False) except ImportError: # django CMS 3.3 and below from cms.plugin_rendering import render_placeholder rendered = render_placeholder(instance, context, lang=self.language, editable=False) flat = flatten_context(context) return rendered.strip(), flat
def render_plugin(self, instance, context, placeholder=None, editable=False): if not placeholder: placeholder = instance.placeholder instance, plugin = instance.get_plugin_instance() if not instance or not plugin.render_plugin: return '' # we'd better pass a flat dict to template.render # as plugin.render can return pretty much any kind of context / dictionary # we'd better flatten it and force to a Context object # flattening the context means that template must be an engine-specific template object # which is guaranteed by get_cached_template if the template returned by # plugin._get_render_template is either a string or an engine-specific template object context = PluginContext(context, instance, placeholder) context = plugin.render(context, instance, placeholder.slot) context = flatten_context(context) template = plugin._get_render_template(context, instance, placeholder) template = self.templates.get_cached_template(template) content = template.render(context) for path in get_cms_setting('PLUGIN_PROCESSORS'): processor = import_string(path) content = processor(instance, placeholder, content, context) if editable: content = self.plugin_edit_template.format(pk=instance.pk, content=content) placeholder_cache = self._rendered_plugins_by_placeholder.setdefault( placeholder.pk, {}) placeholder_cache.setdefault('plugins', []).append(instance) return mark_safe(content)
def render_tag(self, context, plugin, nodelist): """ Renders the block for the plugin and returns the resulting HTML leaving the temmpate context untouched. If the placeholder is editable, the edit script and markup are added to the rendered HTML. """ request = context.get("request") if not plugin or not request: return "" # Add the plugin and its rendered content to an internal context internal_context = flatten_context(context) internal_context["instance"] = plugin internal_context["content"] = nodelist.render(context.new(internal_context)) # Add the edit script and markup to the content, only if the placeholder is editable # and the visited page is the one on which the plugin's placeholder is declared. toolbar = get_toolbar_from_request(request) if plugin.placeholder.page == request.current_page and toolbar.edit_mode_active: return render_to_string(self.template, internal_context) return internal_context["content"]
def toolbar_plugin_processor(instance, placeholder, rendered_content, original_context): from cms.plugin_pool import plugin_pool original_context.push() child_plugin_classes = [] plugin_class = instance.get_plugin_class() if plugin_class.allow_children: inst, plugin = instance.get_plugin_instance() page = original_context['request'].current_page plugin.cms_plugin_instance = inst children = [ plugin_pool.get_plugin(cls) for cls in plugin.get_child_classes(placeholder, page) ] # Builds the list of dictionaries containing module, name and value for the plugin dropdowns child_plugin_classes = get_toolbar_plugin_struct(children, placeholder.slot, placeholder.page, parent=plugin_class) instance.placeholder = placeholder request = original_context['request'] with force_language(request.toolbar.toolbar_language): data = { 'instance': instance, 'rendered_content': rendered_content, 'child_plugin_classes': child_plugin_classes, } # TODO: Remove js_compat once get_action_urls is refactored. data.update(instance.get_action_urls(js_compat=False)) original_context.update(data) plugin_class = instance.get_plugin_class() template = plugin_class.frontend_edit_template output = render_to_string(template, flatten_context(original_context)).strip() original_context.pop() return output
def favorite_button(context, target): user = context['request'].user # do nothing when user isn't authenticated if not user.is_authenticated(): return '' target_model = '.'.join((target._meta.app_label, target._meta.object_name)) undo = False # prepare button to unfave if the user # already faved this object if Favorite.objects.get_favorite(user, target): undo = True context = flatten_context(context) context.update({ 'target_model': target_model, 'target_object_id': target.id, 'undo': undo, 'fav_count': Favorite.objects.for_object(target).count() }) return render_to_string('favit/button.html', context)
def render_plugin(context, instance, placeholder, template, processors=None, current_app=None): """ Renders a single plugin and applies the post processors to it's rendered content. """ if current_app: context["request"].current_app = current_app if not processors: processors = [] if isinstance(template, six.string_types): content = render_to_string(template, flatten_context(context)) elif isinstance(template, Template) or ( hasattr(template, "template") and hasattr(template, "render") and isinstance(template.template, Template) ): content = template.render(context) else: content = "" for processor in iterload_objects(get_cms_setting("PLUGIN_PROCESSORS")): content = processor(instance, placeholder, content, context) for processor in processors: content = processor(instance, placeholder, content, context) for processor in DEFAULT_PLUGIN_PROCESSORS: content = processor(instance, placeholder, content, context) return content
def render_addons(self, context): context.push() context['local_toolbar'] = self clipboard = mark_safe(render_to_string('cms/toolbar/clipboard.html', flatten_context(context))) context.pop() return [clipboard]
def render_placeholder( placeholder, context_to_copy, name_fallback="Placeholder", lang=None, default=None, editable=True, use_cache=True ): """ Renders plugins for a placeholder on the given page using shallow copies of the given context, and returns a string containing the rendered output. Set editable = False to disable front-end editing for this placeholder during rendering. This is primarily used for the "as" variant of the render_placeholder tag. """ from cms.utils.placeholder import get_placeholder_conf, restore_sekizai_context from cms.utils.plugins import get_plugins # these are always called before all other plugin context processors from sekizai.helpers import Watcher if not placeholder: return context = copy(context_to_copy) context.push() request = context["request"] if not hasattr(request, "placeholders"): request.placeholders = [] if placeholder.has_change_permission(request) or not placeholder.cache_placeholder: request.placeholders.append(placeholder) if hasattr(placeholder, "content_cache"): return mark_safe(placeholder.content_cache) page = placeholder.page if placeholder else None # It's kind of duplicate of the similar call in `get_plugins`, but it's required # to have a valid language in this function for `get_fallback_languages` to work if lang: save_language = lang else: lang = get_language_from_request(request) save_language = lang # Prepend frontedit toolbar output if applicable toolbar = getattr(request, "toolbar", None) if ( getattr(toolbar, "edit_mode", False) and getattr(toolbar, "show_toolbar", False) and getattr(placeholder, "is_editable", True) and editable ): from cms.middleware.toolbar import toolbar_plugin_processor processors = (toolbar_plugin_processor,) edit = True else: processors = None edit = False if get_cms_setting("PLACEHOLDER_CACHE") and use_cache: if not edit and placeholder and not hasattr(placeholder, "cache_checked"): cached_value = get_placeholder_cache(placeholder, lang) if cached_value is not None: restore_sekizai_context(context, cached_value["sekizai"]) return mark_safe(cached_value["content"]) if page: template = page.template else: template = None plugins = [plugin for plugin in get_plugins(request, placeholder, template, lang=lang)] # Add extra context as defined in settings, but do not overwrite existing context variables, # since settings are general and database/template are specific # TODO this should actually happen as a plugin context processor, but these currently overwrite # existing context -- maybe change this order? slot = getattr(placeholder, "slot", None) if slot: for key, value in get_placeholder_conf("extra_context", slot, template, {}).items(): if key not in context: context[key] = value content = [] watcher = Watcher(context) content.extend(render_plugins(plugins, context, placeholder, processors)) toolbar_content = "" if edit and editable: # TODO remove ``placeholders`` in 3.3 if not hasattr(request.toolbar, "placeholders"): request.toolbar.placeholders = {} if not hasattr(request.toolbar, "placeholder_list"): request.toolbar.placeholder_list = [] if placeholder.pk not in request.toolbar.placeholders: # TODO remove ``placeholders`` in 3.3 request.toolbar.placeholders[placeholder.pk] = placeholder request.toolbar.placeholder_list.append(placeholder) toolbar_content = mark_safe(render_placeholder_toolbar(placeholder, context, name_fallback, save_language)) if content: content = mark_safe("".join(content)) elif default: # should be nodelist from a template content = mark_safe(default.render(context_to_copy)) else: content = "" context["content"] = content context["placeholder"] = toolbar_content context["edit"] = edit result = render_to_string("cms/toolbar/content.html", flatten_context(context)) changes = watcher.get_changes() if ( placeholder and not edit and placeholder.cache_placeholder and get_cms_setting("PLACEHOLDER_CACHE") and use_cache ): set_placeholder_cache(placeholder, lang, content={"content": result, "sekizai": changes}) context.pop() return result
def render_tag(self, context, name, nodelist): # render JS rendered_contents = nodelist.render(context) toolbar = render_to_string('lightcms/toolbar/toolbar.html', flatten_context(context)) # return the toolbar content and the content below return '%s\n%s' % (toolbar, rendered_contents)
def render_placeholder(placeholder, context_to_copy, name_fallback="Placeholder", lang=None, default=None, editable=True, use_cache=True): """ Renders plugins for a placeholder on the given page using shallow copies of the given context, and returns a string containing the rendered output. Set editable = False to disable front-end editing for this placeholder during rendering. This is primarily used for the "as" variant of the render_placeholder tag. """ from cms.utils.placeholder import get_placeholder_conf, restore_sekizai_context from cms.utils.plugins import get_plugins # these are always called before all other plugin context processors from sekizai.helpers import Watcher if not placeholder: return context = copy(context_to_copy) context.push() request = context['request'] if not hasattr(request, 'placeholders'): request.placeholders = {} # Prepend frontedit toolbar output if applicable try: toolbar = getattr(request, 'toolbar', None) except AttributeError: toolbar = None if (toolbar and toolbar.edit_mode and toolbar.show_toolbar and placeholder.is_editable and editable): from cms.middleware.toolbar import toolbar_plugin_processor processors = (toolbar_plugin_processor,) edit = True else: processors = None edit = False if edit: perms = (placeholder.has_change_permission(request) or not placeholder.cache_placeholder) if not perms or placeholder.slot not in request.placeholders: request.placeholders[placeholder.slot] = (placeholder, perms) else: request.placeholders[placeholder.slot] = ( placeholder, perms and request.placeholders[placeholder.slot][1] ) else: request.placeholders[placeholder.slot] = ( placeholder, False ) if hasattr(placeholder, 'content_cache'): return mark_safe(placeholder.content_cache) page = placeholder.page if placeholder else None if page: site_id = page.site_id else: site_id = get_site_id(None) # It's kind of duplicate of the similar call in `get_plugins`, but it's required # to have a valid language in this function for `get_fallback_languages` to work if lang: save_language = lang else: lang = get_language_from_request(request) save_language = lang use_cache = use_cache and not request.user.is_authenticated() if get_cms_setting('PLACEHOLDER_CACHE') and use_cache: if not edit and placeholder and not hasattr(placeholder, 'cache_checked'): cached_value = get_placeholder_cache(placeholder, lang, site_id, request) if cached_value is not None: restore_sekizai_context(context, cached_value['sekizai']) return mark_safe(cached_value['content']) if page: template = page.template else: template = None plugins = [plugin for plugin in get_plugins(request, placeholder, template, lang=lang)] # Add extra context as defined in settings, but do not overwrite existing context variables, # since settings are general and database/template are specific # TODO this should actually happen as a plugin context processor, but these currently overwrite # existing context -- maybe change this order? slot = getattr(placeholder, 'slot', None) if slot: for key, value in get_placeholder_conf("extra_context", slot, template, {}).items(): if key not in context: context[key] = value content = [] watcher = Watcher(context) content.extend(render_plugins(plugins, context, placeholder, processors)) toolbar_content = '' if edit and editable: if not hasattr(request.toolbar, 'placeholder_list'): request.toolbar.placeholder_list = [] if placeholder not in request.toolbar.placeholder_list: request.toolbar.placeholder_list.append(placeholder) toolbar_content = mark_safe(render_placeholder_toolbar(placeholder, context, name_fallback, save_language)) if content: content = mark_safe("".join(content)) elif default: # should be nodelist from a template content = mark_safe(default.render(context_to_copy)) else: content = '' context['content'] = content context['placeholder'] = toolbar_content context['edit'] = edit result = render_to_string("cms/toolbar/content.html", flatten_context(context)) changes = watcher.get_changes() if use_cache and placeholder.cache_placeholder and get_cms_setting('PLACEHOLDER_CACHE'): content = {'content': result, 'sekizai': changes} set_placeholder_cache(placeholder, lang, site_id, content=content, request=request) context.pop() return result
def test_cms_templates_with_pathsep(self): from sekizai.context import SekizaiContext context = flatten_context(SekizaiContext()) self.assertEqual(render_to_string('subdir/template.html', context).strip(), 'test')
def test_cms_templates_with_pathsep(self): from sekizai.context import SekizaiContext context = flatten_context(SekizaiContext()) self.assertEqual( render_to_string('subdir/template.html', context).strip(), 'test')
def render_placeholder(placeholder, context_to_copy, name_fallback="Placeholder", lang=None, default=None, editable=True, use_cache=True): """ Renders plugins for a placeholder on the given page using shallow copies of the given context, and returns a string containing the rendered output. Set editable = False to disable front-end editing for this placeholder during rendering. This is primarily used for the "as" variant of the render_placeholder tag. """ from cms.utils.placeholder import get_placeholder_conf, restore_sekizai_context from cms.utils.plugins import get_plugins # these are always called before all other plugin context processors from sekizai.helpers import Watcher if not placeholder: return context = copy(context_to_copy) context.push() request = context['request'] if not hasattr(request, 'placeholders'): request.placeholders = [] if placeholder.has_change_permission( request) or not placeholder.cache_placeholder: request.placeholders.append(placeholder) if hasattr(placeholder, 'content_cache'): return mark_safe(placeholder.content_cache) page = placeholder.page if placeholder else None # It's kind of duplicate of the similar call in `get_plugins`, but it's required # to have a valid language in this function for `get_fallback_languages` to work if lang: save_language = lang else: lang = get_language_from_request(request) save_language = lang # Prepend frontedit toolbar output if applicable toolbar = getattr(request, 'toolbar', None) if (getattr(toolbar, 'edit_mode', False) and getattr(toolbar, "show_toolbar", False) and getattr(placeholder, 'is_editable', True) and editable): from cms.middleware.toolbar import toolbar_plugin_processor processors = (toolbar_plugin_processor, ) edit = True else: processors = None edit = False if get_cms_setting('PLACEHOLDER_CACHE') and use_cache: if not edit and placeholder and not hasattr(placeholder, 'cache_checked'): cached_value = get_placeholder_cache(placeholder, lang) if cached_value is not None: restore_sekizai_context(context, cached_value['sekizai']) return mark_safe(cached_value['content']) if page: template = page.template else: template = None plugins = [ plugin for plugin in get_plugins(request, placeholder, template, lang=lang) ] # Add extra context as defined in settings, but do not overwrite existing context variables, # since settings are general and database/template are specific # TODO this should actually happen as a plugin context processor, but these currently overwrite # existing context -- maybe change this order? slot = getattr(placeholder, 'slot', None) if slot: for key, value in get_placeholder_conf("extra_context", slot, template, {}).items(): if key not in context: context[key] = value content = [] watcher = Watcher(context) content.extend(render_plugins(plugins, context, placeholder, processors)) toolbar_content = '' if edit and editable: if not hasattr(request.toolbar, 'placeholder_list'): request.toolbar.placeholder_list = [] if placeholder not in request.toolbar.placeholder_list: request.toolbar.placeholder_list.append(placeholder) toolbar_content = mark_safe( render_placeholder_toolbar(placeholder, context, name_fallback, save_language)) if content: content = mark_safe("".join(content)) elif default: # should be nodelist from a template content = mark_safe(default.render(context_to_copy)) else: content = '' context['content'] = content context['placeholder'] = toolbar_content context['edit'] = edit result = render_to_string("cms/toolbar/content.html", flatten_context(context)) changes = watcher.get_changes() if placeholder and not edit and placeholder.cache_placeholder and get_cms_setting( 'PLACEHOLDER_CACHE') and use_cache: set_placeholder_cache(placeholder, lang, content={ 'content': result, 'sekizai': changes }) context.pop() return result