首页 > 解决方案 > 模板中的 Django 渲染 HTML 给出字节

问题描述

在我的 django 应用程序中,我手动渲染页面并将其提供给模板以包含:

def get_context_data(self, **kwargs):
    page = render(self.request, test_absolute_path, context, content_type=None, status=None, using=None)
    soup = BeautifulSoup(page.content, 'html.parser')
    soup.dosomestuff()
    page.content = str(soup.decode()).replace('\n','')
    context['subtests'].append(page)
    return context

然后使用safe标记将呈现的 HTML 包含到模板中:

 {{ page.content | safe }}

我确实包含了我的标签,但文本看起来像一个字节数组,并且由于某种原因编码不正确:

b'
My text Cat\xc3\xa9gorisation S\xc3\xa9quqsdazeences R\xc3\xa9ponses associ\xc3\xa9es Fluidit\xc3\xa9 

请注意,我还必须\n用代码中的任何内容替换所有内容。

编辑 :

我注意到在 ascii 中对汤进行编码至少会打印所有字符,但我仍然无法摆脱\nor b

page.content = soup.encode('ascii')

标签: djangodjango-templates

解决方案


page.content总是返回字节数组。一种选择是在模板标签中调用解码。

{{ page.content.decode | safe }}

另一种是使用不同的名称,如下所示。

def get_context_data(self, **kwargs):
    page = render(self.request, 'viewbase/sub_page.html', context,
            content_type=None, status=None, using=None)
    soup = BeautifulSoup(page.content, 'html.parser')
    soup.dosomestuff()
    page.new_content = soup.decode()
    context['subtests'].append(page)
    return context

这样,模板就有了下面的标签。

{{ page.new_content | safe }}

或者直接将内容而不是页面放在上下文中,以防您不需要页面中的任何其他内容。

    context['subtests'].append(soup)

{{ soup | safe }}

推荐阅读