Setting fig.alt using knitr::knit_hooks

I'm trying to write a function that is used inside a Rmd code chunk. It should check if the code chunk it currently resides in has set fig.alt. If it does not, it should set the fig.alt to a specified value. If it is set, then leave as is.

Here is what I have so far after my prolonged struggles. I've been trying to follow the knitr Hooks page, to no avail..

dummy_function <- function() {
  current_chunk <- knitr::knit_hooks$get('chunk')

  knitr::knit_hooks$set(chunk = function(x, options) {
    if (is.null(options$fig.alt)) {
      options$fig.alt = "Hello World!"
    } else {
      return(current_chunk(x, options))
    }
  })
  plot(pressure)
}

When I run dummy_function() in a code chunk that doesn't set fig.alt, it just returns "Hello World" without running plot(pressure) nor setting the fig.alt :

Screenshot 2023-09-26 at 4.37.31 PM

Another thing I've tried is:

dummy_function <- function() {
 knitr::opts_hooks$set(fig.alt = function(options) {
  if (options$fig.alt) {
    options$fig.alt = "It worked!"
  }
  options
})
  plot(pressure)
}

This sets the fig.alt to be TRUE, instead of It worked

For reference this is also asked on Github at opts_current$set should error · Issue #1798 · yihui/knitr · GitHub
Use case for this is I believe: Supply google slide notes to fig.alt · Issue #119 · jhudsl/ottrpal · GitHub

This is for context.

Answer I gave there about modifying options in knitr

using options hook is often the first thing to try

---
title: test
output: html_document
---

```{r}
knitr::opts_hooks$set(engine = function(options) {
  # do nothing for non R chunk
  if (tolower(options$engine) != "r") return(options)
  # if not fig.alt, then use a default one
  if(is.null(options$fig.alt)) {
    options$fig.alt = "individual slide notes"
  }
  options
})
```

```{r}
knitr::opts_current$get("fig.alt")
```

Options hooks will be run for each chunks, and so you could conditionally check some specific thing for your use case.

Maybe @yihui will have more advice regarding Supply google slide notes to fig.alt · Issue #119 · jhudsl/ottrpal · GitHub use case.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.