[英]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編碼湯至少可以打印所有字符,但是我仍然無法擺脫\\n
或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 }}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.