Create code snippets for various languages in rmardown programmatically

淺唱寂寞╮ 提交于 2021-01-07 03:54:53

问题


I try to create Code snippet programmatically through a provided Parameter but Keep the target programming language dynamic.

What i tried: Following https://stackoverflow.com/a/64855295/8538074 i know i could use opts <- knitr::opts_chunk$get() which will include an engine opts$engine which could be tried to bet set to "SQL".

I guess that sthg like that should work because of: https://github.com/yihui/knitr-examples/blob/master/115-engine-sql.md https://github.com/yihui/knitr-examples/blob/master/115-engine-sql.Rmd

(but i would need to render it from code since i handover the corresponding code string via the params of the rmarkdown file)

My best try:

---
title: "xx"
output: html_document
params:
  code: list(language = "SQL", code_string = "SELECt * FROM tbl LIMIT 15")
---
   

```{r setup, include=FALSE}
hook <- knitr::hooks_html()$source
opts <- knitr::opts_chunk$get()

language <- params$code$code$language
opts$engine <- language

code_string <- params$code$code_string
cat(hook(code_string, options = opts))

```

回答1:


Based on Martin´s comment:

---
title: "xx"
output: html_document
params:
  code: list(language = "SQL", code_string = "SELECT * FROM tbl LIMIT 15")
---
   

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```


```{r, results = 'asis', echo = F}
chunks <- eval(parse(text = params$code))
hook <- knitr::hooks_html()$source
opts <- knitr::opts_chunk$get()

opts$highlight <- FALSE
code_string <- chunks$code_string
cat(hook(code_string, options = opts))

```


来源:https://stackoverflow.com/questions/64942640/create-code-snippets-for-various-languages-in-rmardown-programmatically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!