Making external links open in a new window in wagtail

后端 未结 2 806
情深已故
情深已故 2021-01-05 03:25

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

@hooks.register(\'after_edit_page\')
def do_after_page_edit(request         


        
2条回答
  •  一个人的身影
    2021-01-05 04:08

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

    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');
    });        
    

    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.

提交回复
热议问题