获取在 knitr 中编织的文档类型

Getting document type that is knitted in knitr

我在 knitr 中使用 code externalization。我有一个包含代码的 myRcode.R 文件,我有两种要生成的报告。一份乳胶文件 (myLatexFile.RNW) 和一份 html 文件 (myHtmlFile.RMD)。两者都从 myRcode.R 文件中调用块。我想根据调用块的扩展获得不同的输出。

现在,我的解决方案是这样的:

library(stringr)
if (str_sub(current_input(),-3,-1) == "Rmd") {
  cat("HTML file...")
} else if (str_sub(current_input(),-3,-1) == "Rnw") 
  cat("LATEX file...")

但是 knitr 中应该有一个获取文件类型的本机函数。我找不到它。 knitr中有这样的功能吗?

正如所指出的, knitr 1.18 introduced以下函数

knitr::is_html_output()
knitr::is_latex_output()

在编译时检查输出是 HTML 还是 LaTeX,以及 return TRUE/FALSE。像下面这样的东西会起作用:

if (knitr::is_html_output()) {
  cat("HTML file...")
} else if (knitr::is_latex_output()) { 
  cat("LATEX file...")
}