首页 > 解决方案 > RMarkdown html _site.yml navbar href 链接,在新选项卡中打开 target="_blank"

问题描述

在 R Markdown HTML _site.yml 页面上苦苦挣扎。在我的导航栏中,我有 href 指向不同的网站链接,我不知道在哪里包含

target="_blank"

声明,因此链接在新选项卡中打开。Href 链接不遵循 RMarkdowns _site.yml 文件中的正常 html 格式。

    - text: "TWITTER"
      icon: fa-twitter
      href: https://twitter.com
    - text: "GITHUB"
      icon: fa-github
      href: https://github.com
    - text: "SLACK"
      icon: fa-slack
      href: https://slack.com

标签: htmlrr-markdown

解决方案


基本上最好的做法是创建一个自动添加target="_blank"到任何外部链接的 js 代码。并考虑到生成的内部链接rmarkdown是相对的事实。我们可以很容易地创建一个正则表达式来测试外部链接是否存在,如果发现则追加target="_blank"

首先创建:links.js

(function() {
  for (const link of document.getElementsByTagName('a')) {
    if (/^(https?:)?\/\//.test(link.getAttribute('href'))) link.target = '_blank';
  }
})();

将脚本标签添加到 include_footer.html

<script type="text/javascript" src="links.js"></script>

在 _site.yml 中包含 include_footer

output:
  html_document:
    includes:
      after_body: include_footer.html

推荐阅读