django - 模板中的 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 中对汤进行编码至少会打印所有字符,但我仍然无法摆脱\n
or b
:
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 }}
推荐阅读
- python - 如何使用括号在换行符中打印列表元素?
- angular - 有没有人用过 http 中 rxjs 的 toPromise 和 Promise.all
- react-native - 从网络获取数据时优化 React-Native 应用程序内存
- android - GroupModel 不能转换为另一个模型
- jekyll - 如果扩展名为 name_of_pic.JPG,为什么无法加载帖子图片?
- node.js - “on”和“emit”功能是干什么用的?
- amazon-web-services - 任务节点上具有多个横向扩展规则的 EMR 自动扩展行为
- qt - qml qt 5.12 在一个程序中使用模块 controls1 和 controls2
- php - 可以使用blade.php 打开本地文件并显示内容吗?拉拉维尔
- mysql - 将表复制到另一个数据库后,表大小减少到 90%