在Wagtail中在新窗口中打开外部链接

在Wagtail中在新窗口中打开外部链接

问题描述:

我最近实现了将 target = _ blank 添加到这样的外部链接:

I recently implemented adding target="_blank" to external links like this:

@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}),
    }

问题:


  1. 美丽的s oup弄乱了输出,添加了 html,head&正文标签-不要放html,head和body标签自动,beautifulsoup

它也与嵌入标签-如何使BeautifulSoup 4尊重自闭合标签?

使用我cr脚的 fix 手动将输出的一部分替换为空白字符串。

Hence my crappy "fix" manually replacing parts of the output with blank strings.

问题:

执行此操作的正确和最佳方法是什么?

What is the correct and best way to do this?

一直在努力解决相同的问题,无法使用wagtailhooks来解决。我最初的解决方案是使用过滤器来处理base.html中的内容。剪切代码段的过滤器放在内容块中时效果很好,例如:

Have been struggling with the same problem and couldn’t achieve it using wagtailhooks. My initial solution was to manipulate the content in base.html, using a filter. The filter to cut pieces of code works perfectly when placed in the content block, example:

{{ self.body|cut: ‘ href="http:’}}

上面的过滤器删除了部分内容,但不幸的是替换了'不能用作过滤器(我使用的是Python 3.x)。因此,我的下一种方法是构建一个custom_filter来创建 replace作为过滤器选项。长话短说:它部分起作用,但仅当内容从将原始的 StreamValue数据类型转换为字符串。此转换导致显示了所有html标签的内容,因此替换未导致html正常工作。我无法再次将内容恢复为StreamValue,也没有其他Python数据类型对
最终JQuery为我完成了工作:

Above filter deletes parts of the content, but unfortunately ‘replace’ is not available as a filter (I´m using Python 3.x). Therefor my next approach was building a custom_filter to create ´replace´ as filter option. Long story short: It partly worked but only if the content was converted from the original ‘StreamValue’ datatype to ‘string’. This conversion resulted in content with all html tags shown, so the replacement did not result in working html. I couldn´t get the content back to StreamValue again and no other Python datatype remedied the issue. Eventually JQuery got the job done for me:

$(document).ready(function(){
$('a[href^="http://"]').attr('target', '_blank');
});        

此代码将'target = _ blank'添加到每个链接包含 http://,因此所有内部链接都保留在现有标签中。它需要放置在base.html(或类似文件)的末尾,当然,您需要在运行它之前加载JQuery。
此处得到了我的答案。
不知道JQuery是否是正确的最佳方法,但它对我的魅力很小,只需最少的编码。

This code adds ‘target="_blank"’ to each link containing ‘http://’, so all internal links stay in the existing tab. It needs to be placed at the end of your base.html (or similar) and of course you need to load JQuery before you run it. Got my answer from here . Don’t know if JQuery is the correct and best way to do it, but it works like a charm for me with minimal coding.