Search code examples
djangodjango-1.10

Using RenderContext in render_to_string in Django 1.10


I'm upgrading a project to Django 1.10 and trying to change the following template tag (simplified)

@register.simple_tag(takes_context=True)
def render_svg(context, svg_template_file_name, *args, **kwargs):
    svg_string = render_to_string(svg_template_file_name, context, request=context.request)

This no longer works since the context passed in is a RenderContext, where the docs state:

If you’re passing a Context in context_instance, pass a dict in the context parameter instead. If you’re passing a RequestContext, pass the request separately in the request parameter.

Which I'm already doing and still would like to make use of the context parameter to render_to_string...

So how can I get a usable dictionary from a RenderContext?


Solution

  • RenderContext's base class, BaseContext, has a function called flatten which will take the array of dictionaries inside a Context object and return a single dictionary

    render_to_string(svg_template_file_name, context, request=context.request)
    

    would need changing to

    render_to_string(svg_template_file_name, context.flatten(), request=context.request)