繁体   English   中英

模板中的Django渲染HTML提供字节

[英]Django Rendering HTML in a template give bytes

在我的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编码汤至少可以打印所有字符,但是我仍然无法摆脱\\nb

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

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 }}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM