I’m building a custom, industry-specific cms (using django). In the backend, webmasters can specify either an internal link, e.g. “/page1” or an external link to use for various navigation elements throughout the website (all use <a> when rendered) . The problem is that I would like internal links to open in the current tab, but external links should use target="_blank" to open a new tab or window.
How can I process the html to accomplish this?
I’d prefer a server-side solution, but am not aware of any clean way to pre-process rendered templates in django. So, I assume the most straightforward way to do this is probably a javascript/jquery solution: a script that runs when each page loads, which adds the target=”_blank” attribute to all external links but not internal links. But I’m not sure how to do this, either.
I’ve been using the following for awhile. Can’t remember where I found it originally:
That adds an
:externaljQuery selector, so then you can just do:The nice part about using the custom selector, is that if you need to modify what contitutes an “external” link, you can change it in one place and not worry about the rest of your code. For instance in my organization, we have certain subdomains that aren’t “external”, but that we still want to open in new windows.