-
Hi everyone, I am trying to get learnr to present an exercise code element with some code inside that is being generated/updated dynamically depending on some GET parameters in the URL when calling the shiny/learnr app. For example, if I load I am able to read in the URL parameters in a
Is there any way this is possible? Or do you have alternative solutions/suggestions? Thanks, |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
It is possible to update the text in a code box dynamically from the Shiny server that runs the learnr tutorial, which means that you could in theory use the query parameters to initialize the code boxes. There are probably more than a few edge cases you'd want to think through (or end up running into). The process for updating an exercise code box from the server isn't very straightforward and it requires writing a little bit of JavaScript. I'd recommend taking a look at my answer to a similar question on Posit Community. First, you'd include a chunk of JavaScript in your learnr document. ```{js echo=FALSE}
//
// A custom Shiny message handler that updates the code in any exercise
// From R you'll send a list(label = "exercise-chunk-label", code = "new code for editor"))
//
Shiny.addCustomMessageHandler('set-exercise-code', function(x) {
var el = $(`.tutorial-exercise[data-label="${x.label}"] .tutorial-exercise-code-editor`)
var exerciseInput = Shiny.inputBindings.bindingNames["tutorial.exerciseInput"].binding
exerciseInput.setValue(el, {code: x.code})
})
``` Then, include this function in your setup chunk or in a chunk with update_exercise <- function(label, code, session = shiny::getDefaultReactiveDomain()) {
session$sendCustomMessage("set-exercise-code", list(label = label, code = code))
} which you can then use to update an exercise using the label of its chunk: update_exercise("plus", "2 + 2") I hope that helps! If you do figure out how to make this work, we'd love to see what you come up with! |
Beta Was this translation helpful? Give feedback.
It is possible to update the text in a code box dynamically from the Shiny server that runs the learnr tutorial, which means that you could in theory use the query parameters to initialize the code boxes. There are probably more than a few edge cases you'd want to think through (or end up running into).
The process for updating an exercise code box from the server isn't very straightforward and it requires writing a little bit of JavaScript. I'd recommend taking a look at my answer to a similar question on Posit Community.
First, you'd include a chunk of JavaScript in your learnr document.