Skip to content

How to evaluate include argument? #10

Open

Description

@wzbillings

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?

Activity

  1. wzbillings commented on Mar 18, 2024

    @wzbillings
    Author

    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.

  2. cderv commented on Mar 20, 2024

    @cderv
    Contributor

    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

      
    ```{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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions