问题
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