0

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))

```
Tlatwork
  • 1,445
  • 12
  • 35
  • First of all there are some errors in your code. Parse the output parameter first just like I answered on the other question: `chunks <- eval(parse(params$code))`. Then you can access `chunks$language` and `chunks$code_string`. I get the error to install highlight by Andre simon when I render the document. You can then try that or set `opts$highglight <- FALSE`. – Martin Schmelzer Nov 26 '20 at 08:08
  • you are right, thanks. I add a self answer in case someone Need it. or would of Course upvote and accept your answer. – Tlatwork Nov 26 '20 at 22:09

1 Answers1

0

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))

```
Tlatwork
  • 1,445
  • 12
  • 35