以编程方式在 rmardown 中为各种语言创建代码片段
我尝试通过提供的参数以编程方式创建代码片段,但保持目标编程语言动态.
I try to create Code snippet programmatically through a provided Parameter but Keep the target programming language dynamic.
我尝试过的:关注 https://stackoverflow.com/a/64855295/8538074我知道我可以使用 opts <- knitr::opts_chunk$get()
这将包括一个可以尝试的引擎 opts$engine
下注设置为SQL".
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".
我想像那样的东西应该起作用,因为:https://github.com/yihui/knitr-示例/blob/master/115-engine-sql.mdhttps://github.com/yihui/knitr-示例/blob/master/115-engine-sql.Rmd
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
(但我需要从代码中渲染它,因为我通过 rmarkdown 文件的参数移交了相应的代码字符串)
(but i would need to render it from code since i handover the corresponding code string via the params of the rmarkdown file)
我最好的尝试:
---
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))
```
基于 Martin 的评论:
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))
```