quarto-ext / include-code-files

Quarto extension to include code from source files.
MIT License
51 stars 5 forks source link

How to evaluate `include` argument? #10

Open wzbillings opened 8 months ago

wzbillings commented 8 months ago

Sometimes it's easier to construct the path to a file in code, for example: model_path = here::here("my-code-file.stan") in a quarto document.

Is it possible to have the include argument of a chunk evaluated?

```{.stan include=model_path}


doesn't appear to evaluate the variable `model_path` correctly. Is there a syntax option to have this variable get evaluated to return the file path, and then have the path parsed correctly as normal?
wzbillings commented 4 months ago

If anyone was curious, you can get this to work with the following syntax:

```{.stan include=`r model_path`}

noting, that as mentioned in #5, whitespace is meaningful. Quarto's syntax highlighting doesn't like this, but it seems to work correctly for me (and the resulting code is highlighted correctly in the output).

Perhaps a similar example could be included in the README? To me, this feature is extremely useful.
cderv commented 4 months ago

To clarify, the syntax

```{.stan include=model_path}

is raw markdown, and will be processed in Lua directly through Pandoc. So if you have a variable with the path you want to include, you need usually to come up with similar logic as any of the output you can produce with R though knitr. 

This means have R code generate the raw mardkown for you - like table function do for R dataframes, or knitr do for plots, or HTML widgets producing raw HTML. 

So you could have a wrapper like this 
````markdown

```{r}
#| include: false
include_code_file <- function(path, language) {
  glue::glue("
     ```{.%language% include=%path%}
     ```", 
     .open = "%", .close = "%")
}

r include_code_file(model_path, "stan")



But indeed knitr inline R code works ok in this case too.