Example #1
0
def render_block_to_string(template_name, block_name, data=None, context=None):
    data = data or {}
    if context:
        context.update(data)
    else:
        context = RequestContext(default_request(), data)

    t = loader.get_template(template_name)
    with context.bind_template(t.template):
        t.template.render(context)

        to_visit = list(
            t.template.nodelist
        )  # Copier la liste car la liste de nœuds du template est globale (Django 1.10)
        while to_visit:
            node = to_visit.pop(
            )  # ici on modifie la liste, d'où la nécessité de la copier auparavant
            if isinstance(node, BlockNode) and node.name == block_name:
                return node.render(context)
            elif hasattr(node, 'nodelist'):
                to_visit += node.nodelist
            if isinstance(node, (ExtendsNode, MacroRoot)):
                to_visit += node.get_parent(context).nodelist

    raise RuntimeError("Block not found: {0}".format(block_name))
Example #2
0
def django_render_block(template, block_name, context, request=None):
    # Create a Django Context.
    if request:
        context_instance = RequestContext(request)
        context_instance.push(context)
    else:
        context_instance = Context(context)

    # Get the underlying django.template.base.Template object.
    template = template.template

    # Bind the template to the context.
    with context_instance.bind_template(template):
        # Before trying to render the template, we need to traverse the tree of
        # parent templates and find all blocks in them.
        parent_template = _build_block_context(template, context_instance)

        try:
            return _render_template_block(template, block_name, context_instance)
        except BlockNotFound:
            # The block wasn't found in the current template.

            # If there's no parent template (i.e. no ExtendsNode), re-raise.
            if not parent_template:
                raise

            # Check the parent template for this block.
            return _render_template_block(
                parent_template, block_name, context_instance)
Example #3
0
class ContextProcessorTestCase(APITestCase):

    def setUp(self):
        self.request = mock.Mock()
        self.request.session = {}
        self.template = Template("My name is...")
        self.context = RequestContext(self.request)

    def test_context_added_with_context_processor(self):
        with mock.patch('kolibri.auth.api.SessionViewSet.get_session', return_value={"context": True}):
            with self.context.bind_template(self.template):
                self.assertEqual(json.loads(self.context['session'])['context'], True)

    def tearDown(self):
        self.request = None
        self.template = None
        self.context = None
Example #4
0
def get_last_content(request, page_id):
    """Get the latest content for a particular type"""
    content_type = request.GET.get('content_type')
    language_id = request.GET.get('language_id')
    page = get_object_or_404(Page, pk=page_id)
    placeholders = get_placeholders(page.get_template())
    _template = template.loader.get_template(page.get_template())
    for placeholder in placeholders:
        if placeholder.name == content_type:
            context = RequestContext(request, {
                'current_page': page,
                'lang': language_id
            })
            with context.bind_template(_template.template):
                content = placeholder.render(context)
                return HttpResponse(content)
    raise Http404
Example #5
0
def get_last_content(request, page_id):
    """Get the latest content for a particular type"""
    content_type = request.GET.get('content_type')
    language_id = request.GET.get('language_id')
    page = get_object_or_404(Page, pk=page_id)
    placeholders = get_placeholders(page.get_template())
    _template = template.loader.get_template(page.get_template())
    for placeholder in placeholders:
        if placeholder.name == content_type:
            context = RequestContext(request, {
                'current_page': page,
                'lang': language_id
            })
            with context.bind_template(_template.template):
                content = placeholder.render(context)
                return HttpResponse(content)
    raise Http404
Example #6
0
    def render_plugin(self, page, lang, plugin, edit=False):
        """
        Renders a single plugin using CMSPlugin.render_plugin

        :param page: Page object
        :param lang: Current language
        :param plugin: Plugin instance
        :param edit: Enable edit mode for rendering
        :return: Rendered plugin
        """
        request = self.get_page_request(page, self.user, lang=lang, edit=edit)
        context = RequestContext(request)
        try:
            template = get_template(page.get_template()).template
            with context.bind_template(template):
                rendered = plugin.render_plugin(context, plugin.placeholder)
        except AttributeError:
            rendered = plugin.render_plugin(context, plugin.placeholder)
        return rendered
Example #7
0
    def render_plugin(self, page, lang, plugin, edit=False):
        """
        Renders a single plugin using CMSPlugin.render_plugin

        :param page: Page object
        :param lang: Current language
        :param plugin: Plugin instance
        :param edit: Enable edit mode for rendering
        :return: Rendered plugin
        """
        request = self.get_page_request(page, self.user, lang=lang, edit=edit)
        context = RequestContext(request)
        try:
            template = get_template(page.get_template()).template
            with context.bind_template(template):
                rendered = plugin.render_plugin(context, plugin.placeholder)
        except AttributeError:
            rendered = plugin.render_plugin(context, plugin.placeholder)
        return rendered
Example #8
0
def django_render_block(template, block_name, context, request=None):
    # Create a Django Context if needed
    if isinstance(context, Context):
        # Make a copy of the context and reset the rendering state.
        # Trying to re-use a RenderContext in multiple renders can
        # lead to TemplateNotFound errors, as Django will skip past
        # any template files it thinks it has already rendered in a
        # template's inheritance stack.
        context_instance = copy(context)
        context_instance.render_context = RenderContext()
    elif request:
        context_instance = RequestContext(request, context)
    else:
        context_instance = Context(context)

    # Get the underlying django.template.base.Template object.
    template = template.template

    # Bind the template to the context.
    with context_instance.bind_template(template):
        # Before trying to render the template, we need to traverse the tree of
        # parent templates and find all blocks in them.
        parent_template = _build_block_context(template, context_instance)

        try:
            return _render_template_block(template, block_name,
                                          context_instance)
        except BlockNotFound:
            # The block wasn't found in the current template.

            # If there's no parent template (i.e. no ExtendsNode), re-raise.
            if not parent_template:
                raise

            # Check the parent template for this block.
            return _render_template_block(parent_template, block_name,
                                          context_instance)