【问题标题】:Using RenderContext in render_to_string in Django 1.10在 Django 1.10 的 render_to_string 中使用 RenderContext
【发布时间】:2017-04-21 07:40:20
【问题描述】:

我正在将项目升级到 Django 1.10 并尝试更改以下模板标记(简化)

@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)

这不再有效,因为传入的contextRenderContext,其中docs 状态:

如果您在 context_instance 中传递 Context,请改为在 context 参数中传递 dict。如果您要传递 RequestContext,请在请求参数中单独传递请求。

我已经在做并且仍然想将context 参数用于render_to_string...

那么我如何从RenderContext 获取可用的字典?

【问题讨论】:

    标签: django django-1.10


    【解决方案1】:

    RenderContext 的基类 BaseContext 有一个名为 flatten 的函数,它将获取 Context 对象中的字典数组并返回单个字典

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

    需要改成

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-04
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 2020-02-10
      • 2020-01-20
      • 2016-08-25
      相关资源
      最近更新 更多