我最近实现了像这样添加 target="_blank"
到外部链接:
@hooks.register('after_edit_page')
def do_after_page_edit(request, page):
if hasattr(page, "body"):
soup = BeautifulSoup(page.body)
for a in soup.findAll('a'):
if hasattr(a, "href"):
a["target"] = "_blank"
page.body = str(soup)
page.body = page.body.replace("<html><head></head><body>", "")
page.body = page.body.replace("</body></html>", "")
page.body = page.body.replace("></embed>", "/>")
page.save()
@hooks.register('construct_whitelister_element_rules')
def whitelister_element_rules():
return {
'a': attribute_rule({'href': check_url, 'target': True}),
}
问题:
如何正确并最好地解决这个问题?
Beautiful Soup会干扰输出,添加
html,head和body
标签 - 不要自动添加 HTML、Head 和 Body 标签,使用 Beautiful Soup它还会影响嵌入标签 - 如何让BeautifulSoup 4尊重自关闭标签?
因此,我的固定方式是用空字符串手动替换输出的部分。
target
属性只需要编辑模板即可。其他选项,如使用JS也可以工作,但那并不是特定于Wagtail的方式。 - Thibaud Colas