Ejemplo n.º 1
0
    def test_processors(self):
        """
        Tests that default plugin context processors are working, that plugin processors and plugin context processors
        can be defined in settings and are working and that extra plugin context processors can be passed to PluginContext.
        """

        def test_passed_plugin_context_processor(instance, placeholder, context):
            return {"test_passed_plugin_context_processor": "test_passed_plugin_context_processor_ok"}

        t = (
            u"{% load cms_tags %}"
            + u"{{ plugin.counter }}|{{ plugin.instance.body }}|{{ test_passed_plugin_context_processor }}|{{ test_plugin_context_processor }}"
        )
        instance, plugin = CMSPlugin.objects.all()[0].get_plugin_instance()
        instance.render_template = Template(t)
        context = PluginContext(
            {"original_context_var": "original_context_var_ok"},
            instance,
            self.test_placeholders["main"],
            processors=(test_passed_plugin_context_processor,),
        )
        plugin_rendering._standard_processors = {}
        c = render_plugins((instance,), context, self.test_placeholders["main"])
        r = "".join(c)
        self.assertEqual(
            r,
            u"1|"
            + self.test_data["text_main"]
            + "|test_passed_plugin_context_processor_ok|test_plugin_context_processor_ok|"
            + self.test_data["text_main"]
            + "|main|original_context_var_ok|test_plugin_processor_ok|"
            + self.test_data["text_main"]
            + "|main|original_context_var_ok",
        )
        plugin_rendering._standard_processors = {}
Ejemplo n.º 2
0
    def test_processors(self):
        """
        Tests that default plugin context processors are working, that plugin processors and plugin context processors
        can be defined in settings and are working and that extra plugin context processors can be passed to PluginContext.
        """
        with SettingsOverride(
                CMS_PLUGIN_PROCESSORS=('cms.tests.rendering.sample_plugin_processor',),
                CMS_PLUGIN_CONTEXT_PROCESSORS=('cms.tests.rendering.sample_plugin_context_processor',),
        ):
            def test_passed_plugin_context_processor(instance, placeholder, context):
                return {'test_passed_plugin_context_processor': 'test_passed_plugin_context_processor_ok'}

            t = u'{% load cms_tags %}' + \
                u'{{ plugin.counter }}|{{ plugin.instance.body }}|{{ test_passed_plugin_context_processor }}|{{ test_plugin_context_processor }}'
            instance, plugin = CMSPlugin.objects.all()[0].get_plugin_instance()
            instance.render_template = Template(t)
            context = PluginContext({'original_context_var': 'original_context_var_ok'}, instance,
                                    self.test_placeholders['main'], processors=(test_passed_plugin_context_processor,))
            plugin_rendering._standard_processors = {}
            c = render_plugins((instance,), context, self.test_placeholders['main'])
            r = "".join(c)
            self.assertEqual(r, u'1|' + self.test_data[
                'text_main'] + '|test_passed_plugin_context_processor_ok|test_plugin_context_processor_ok|' +
                                self.test_data['text_main'] + '|main|original_context_var_ok|test_plugin_processor_ok|' + self.test_data[
                                    'text_main'] + '|main|original_context_var_ok')
            plugin_rendering._standard_processors = {}
Ejemplo n.º 3
0
    def test_processors(self):
        """
        Tests that default plugin context processors are working, that plugin processors and plugin context processors
        can be defined in settings and are working and that extra plugin context processors can be passed to PluginContext.
        """
        def test_passed_plugin_context_processor(instance, placeholder,
                                                 context):
            return {
                'test_passed_plugin_context_processor':
                'test_passed_plugin_context_processor_ok'
            }

        t = u'{% load cms_tags %}' + \
            u'{{ plugin.counter }}|{{ plugin.instance.body }}|{{ test_passed_plugin_context_processor }}|{{ test_plugin_context_processor }}'
        instance, plugin = CMSPlugin.objects.all()[0].get_plugin_instance()
        instance.render_template = Template(t)
        context = PluginContext(
            {'original_context_var': 'original_context_var_ok'},
            instance,
            self.test_placeholders['main'],
            processors=(test_passed_plugin_context_processor, ))
        plugin_rendering._standard_processors = {}
        c = render_plugins((instance, ), context,
                           self.test_placeholders['main'])
        r = "".join(c)
        self.assertEqual(
            r, u'1|' + self.test_data['text_main'] +
            '|test_passed_plugin_context_processor_ok|test_plugin_context_processor_ok|'
            + self.test_data['text_main'] +
            '|main|original_context_var_ok|test_plugin_processor_ok|' +
            self.test_data['text_main'] + '|main|original_context_var_ok')
        plugin_rendering._standard_processors = {}
Ejemplo n.º 4
0
def _show_placeholder_for_page(context,
                               placeholder_name,
                               page_lookup,
                               lang=None,
                               site=None,
                               cache_result=True):
    """
    Shows the content of a page with a placeholder name and given lookup
    arguments in the given language.
    This is useful if you want to have some more or less static content that is
    shared among many pages, such as a footer.

    See _get_page_by_untyped_arg() for detailed information on the allowed types
    and their interpretation for the page_lookup argument.
    """
    validate_placeholder_name(placeholder_name)

    request = context.get('request', False)
    site_id = get_site_id(site)

    if not request:
        return {'content': ''}
    if lang is None:
        lang = get_language_from_request(request)

    content = None

    if cache_result:
        base_key = _get_cache_key('_show_placeholder_for_page', page_lookup,
                                  lang, site_id)
        cache_key = _clean_key('%s_placeholder:%s' %
                               (base_key, placeholder_name))
        content = cache.get(cache_key)

    if not content:
        page = _get_page_by_untyped_arg(page_lookup, request, site_id)
        if not page:
            return {'content': ''}
        try:
            placeholder = page.placeholders.get(slot=placeholder_name)
        except PlaceholderModel.DoesNotExist:
            if settings.DEBUG:
                raise
            return {'content': ''}
        baseqs = get_cmsplugin_queryset(request)
        plugins = baseqs.filter(
            placeholder=placeholder,
            language=lang,
            placeholder__slot__iexact=placeholder_name,
            parent__isnull=True).order_by('position').select_related()
        c = render_plugins(plugins, context, placeholder)
        content = "".join(c)

    if cache_result:
        cache.set(cache_key, content, settings.CMS_CACHE_DURATIONS['content'])

    if content:
        return {'content': mark_safe(content)}
    return {'content': ''}
Ejemplo n.º 5
0
def _show_placeholder_for_page(context, placeholder_name, page_lookup, lang=None,
        site=None, cache_result=True):
    """
    Shows the content of a page with a placeholder name and given lookup
    arguments in the given language.
    This is useful if you want to have some more or less static content that is
    shared among many pages, such as a footer.

    See _get_page_by_untyped_arg() for detailed information on the allowed types
    and their interpretation for the page_lookup argument.
    """
    validate_placeholder_name(placeholder_name)

    request = context.get('request', False)
    site_id = get_site_id(site)

    if not request:
        return {'content': ''}
    if lang is None:
        lang = get_language_from_request(request)

    content = None

    if cache_result:
        base_key = _get_cache_key('_show_placeholder_for_page', page_lookup, lang, site_id)
        cache_key = _clean_key('%s_placeholder:%s' % (base_key, placeholder_name))
        content = cache.get(cache_key)

    if not content:
        page = _get_page_by_untyped_arg(page_lookup, request, site_id)
        if not page:
            return {'content': ''}
        try:
            placeholder = page.placeholders.get(slot=placeholder_name)
        except PlaceholderModel.DoesNotExist:
            if settings.DEBUG:
                raise
            return {'content': ''}
        baseqs = get_cmsplugin_queryset(request)
        plugins = baseqs.filter(
            placeholder=placeholder,
            language=lang,
            placeholder__slot__iexact=placeholder_name,
            parent__isnull=True
        ).order_by('position').select_related()
        c = render_plugins(plugins, context, placeholder)
        content = "".join(c)

    if cache_result:
        cache.set(cache_key, content, settings.CMS_CACHE_DURATIONS['content'])

    if content:
        return {'content': mark_safe(content)}
    return {'content': ''}
Ejemplo n.º 6
0
 def render(self, context, instance, placeholder):
     context.update({
         'placeholder': placeholder,
         'gallery': instance})
     
     context.update({
         'plugins': render_plugins(instance.cmsplugin_set.filter(parent=instance).order_by('position'),
                                   context, placeholder)
     })
     
     return context
def index_plugins(placeholder):
    try:
        if placeholder:
            out = render_plugins(placeholder.cmsplugin_set.all(),
                                 SekizaiContext(),
                                 None)
            out = "\n".join(out)
        else:
            out = ""
    except (NoReverseMatch,):
        out = ""
    return mark_safe(unescape(striptags2(out)).strip())
Ejemplo n.º 8
0
    def render(self, context, instance, placeholder):
        context.update({
            'placeholder': placeholder,
            'gallery': instance})

        context.update({
            'plugins': render_plugins(
                instance.get_children().order_by('position','id'),
                context, placeholder)
        })

        return context
Ejemplo n.º 9
0
 def render(self, context, instance, placeholder):
     # TODO: once we drop 2.3.x support we can just use the "render_plugin" templatetag
     #       instead of rendering html here.
     plugins = get_plugins(context['request'], instance.stack.content)
     processors = ()
     html_content = mark_safe(u"".join(render_plugins(plugins, context, placeholder, processors)))
     context.update({
         'instance': instance,
         'placeholder': placeholder,
         'content': html_content,
     })
     return context
Ejemplo n.º 10
0
    def render(self, context, instance, placeholder):

        context.update({"placeholder": placeholder, "gallery": instance})

        context.update(
            {
                "plugins": render_plugins(
                    instance.cmsplugin_set.filter(parent=instance).order_by("position"), context, placeholder
                )
            }
        )

        return context
Ejemplo n.º 11
0
def render_plugins_for_context(placeholder_name, page, context_to_copy, width=None):
    """
    renders plugins for the given named placedholder and page using shallow copies of the 
    given context
    """
    context = copy.copy(context_to_copy) 
    l = get_language_from_request(context['request'])
    request = context['request']
    plugins = [plugin for plugin in get_plugins(request, page) if plugin.placeholder == placeholder_name]
    template = page.template
    extra_context = settings.CMS_PLACEHOLDER_CONF.get("%s %s" % (template, placeholder_name), {}).get("extra_context", None)
    if not extra_context:
        extra_context = settings.CMS_PLACEHOLDER_CONF.get(placeholder_name, {}).get("extra_context", None)
    if extra_context:
        context.update(extra_context)
    if width:
        # this may overwrite previously defined key [width] from settings.CMS_PLACEHOLDER_CONF
        try:
            width = int(width)
            context.update({'width': width,})
        except ValueError:
            pass
    c = []
    edit = False
    if ("edit" in request.GET or request.session.get("cms_edit", False)) and \
            'cms.middleware.toolbar.ToolbarMiddleware' in django_settings.MIDDLEWARE_CLASSES and \
            request.user.is_staff and request.user.is_authenticated() and \
            page.has_change_permission(request):
        edit = True
    if edit:
        installed_plugins = plugin_pool.get_all_plugins(placeholder_name, page)
        name = settings.CMS_PLACEHOLDER_CONF.get("%s %s" % (template, placeholder_name), {}).get("name", None)
        if not name:
            name = settings.CMS_PLACEHOLDER_CONF.get(placeholder_name, {}).get("name", None)
        if not name:
            name = placeholder_name
        name = title(name)
        c.append(render_to_string("cms/toolbar/add_plugins.html", {'installed_plugins':installed_plugins,
                                                               'language':l,
                                                               'placeholder_label':name,
                                                               'placeholder_name':placeholder_name,
                                                               'page':page,
                                                               }))
        from cms.middleware.toolbar import toolbar_plugin_processor
        processors = (toolbar_plugin_processor,)
    else:
        processors = None 
        
    c.extend(render_plugins(plugins, context, placeholder_name, processors))
    
    return "".join(c)
Ejemplo n.º 12
0
def _show_placeholder_for_page(context, placeholder_name, page_lookup, lang=None, site=None, cache_result=True):
    """
    Shows the content of a page with a placeholder name and given lookup
    arguments in the given language.
    This is useful if you want to have some more or less static content that is
    shared among many pages, such as a footer.

    See _get_page_by_untyped_arg() for detailed information on the allowed types
    and their interpretation for the page_lookup argument.
    """
    request = context.get("request", False)
    site_id = get_site_id(site)

    if not request:
        return {"content": ""}
    if lang is None:
        lang = get_language_from_request(request)

    content = None

    if cache_result:
        cache_key = (
            _get_cache_key("_show_placeholder_for_page", page_lookup, lang, site_id)
            + "_placeholder:"
            + placeholder_name
        )
        content = cache.get(cache_key)

    if not content:
        page = _get_page_by_untyped_arg(page_lookup, request, site_id)
        if not page:
            return {"content": ""}
        placeholder = page.placeholders.get(slot=placeholder_name)
        baseqs = get_cmsplugin_queryset(request)
        plugins = (
            baseqs.filter(
                placeholder=placeholder, language=lang, placeholder__slot__iexact=placeholder_name, parent__isnull=True
            )
            .order_by("position")
            .select_related()
        )
        c = render_plugins(plugins, context, placeholder)
        content = "".join(c)

    if cache_result:
        cache.set(cache_key, content, settings.CMS_CONTENT_CACHE_DURATION)

    if content:
        return {"content": mark_safe(content)}
    return {"content": ""}
Ejemplo n.º 13
0
 def save_model(self, request, entry, form, change):
     """Fill the content field with the interpretation
     of the placeholder"""
     context = RequestContext(request)
     #dm
     processors = iterload_objects(settings.CMS_PLUGIN_PROCESSORS)
     plugins = [plugin for plugin in get_plugins(request, entry.content_placeholder)]
     render = render_plugins(plugins, context, entry.content_placeholder)
     content = "".join(render)
     entry.placeholder_render = content
     #entry.placeholder_render = render_placeholder(entry.content_placeholder, context )
     #entry.content = render_placeholder(entry.content_placeholder, context)
     entry.save()
     super(EntryPlaceholderAdmin, self).save_model(
         request, entry, form, change)
Ejemplo n.º 14
0
 def save_model(self, request, entry, form, change):
     """Fill the content field with the interpretation
     of the placeholder"""
     context = RequestContext(request)
     #dm
     processors = iterload_objects(settings.CMS_PLUGIN_PROCESSORS)
     plugins = [
         plugin
         for plugin in get_plugins(request, entry.content_placeholder)
     ]
     render = render_plugins(plugins, context, entry.content_placeholder)
     content = "".join(render)
     entry.placeholder_render = content
     #entry.placeholder_render = render_placeholder(entry.content_placeholder, context )
     #entry.content = render_placeholder(entry.content_placeholder, context)
     entry.save()
     super(EntryPlaceholderAdmin, self).save_model(request, entry, form,
                                                   change)
Ejemplo n.º 15
0
 def render_tag(self, context, code, varname):
     # 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
         return ''
     # TODO: caching?
     if isinstance(code, Stack):
         stack = code
     else:
         stack, __ = stack_models.Stack.objects.get_or_create(code=code, defaults={'name': code})
     # TODO: once we drop 2.3.x support we can just use the "render_plugin" templatetag
     #       instead of rendering html here.
     placeholder = stack.content
     plugins = get_plugins(context['request'], placeholder)
     processors = ()
     rendered_placeholder = mark_safe("".join(render_plugins(plugins, context, placeholder, processors)))
     if varname:
         context[varname] = rendered_placeholder
         rendered_placeholder = u''
     return rendered_placeholder
Ejemplo n.º 16
0
def render_newsy_placeholder(placeholder, context, name_fallback="Placeholder"):
    """
    Renders plugins for a placeholder on the given page using shallow copies of the 
    given context, and returns a string containing the rendered output.
    """
    log.debug('render_newsy_placeholder(placeholder=%s)' % 
              (unicode(placeholder),))
    request = context.get('request', None)
    context.push()
    plugins = list(get_plugins(request, placeholder))
    page = get_newsitem_from_placeholder_if_exists(placeholder)
    if page:
        template = page.template
    else:
        template = None
    # 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)
    extra_context = {}
    if slot:
        extra_context = get_cms_setting('PLACEHOLDER_CONF').get("%s %s" % (template, slot), {}).get("extra_context", None)
        if not extra_context:
            extra_context = get_cms_setting('PLACEHOLDER_CONF').get(slot, {}).get("extra_context", {})
    for key, value in extra_context.items():
        if not key in context:
            context[key] = value

    c = []

    processors = None 
    c.extend(render_plugins(plugins, context, placeholder, processors))
    content = "".join(c)
    context.pop()
    return content
Ejemplo n.º 17
0
 def render_tag(self, context, code, varname):
     # 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
         return ''
     # TODO: caching?
     if isinstance(code, Stack):
         stack = code
     else:
         stack, __ = stack_models.Stack.objects.get_or_create(
             code=code, defaults={'name': code})
     # TODO: once we drop 2.3.x support we can just use the "render_plugin" templatetag
     #       instead of rendering html here.
     placeholder = stack.content
     plugins = get_plugins(context['request'], placeholder)
     processors = ()
     rendered_placeholder = mark_safe("".join(
         render_plugins(plugins, context, placeholder, processors)))
     if varname:
         context[varname] = rendered_placeholder
         rendered_placeholder = u''
     return rendered_placeholder