如何在RMarkdown的代码块中使用JavaScript

如何在RMarkdown的代码块中使用JavaScript

本文介绍了如何在RMarkdown的代码块中使用JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此答案的启发,我想例如在R

input <- data.frame(text = c("a", "b", "c"),
                    page_number = c(3, 5, 6))

根据文本创建一个列表,该列表链接到不同的page_numbers.该解决方案描述了如何在Markdown中使用JavaScript,但是不幸的是,没有在代码块中使用JavaScript(动态创建列表是必需的).

to create a list out of the text, which links to the different page_numbers. The solution describes how to use JavaScript in Markdown but unfortunately not how to use it within code chunks (which is necessary to dynamically create a list).

推荐答案

我喜欢将 htmltools 包用于此类工作.

I like to use the htmltools package for this kind of job.

您可以使用 htmltools :: a()创建HTML锚点.
为了创建幻灯片#2的链接,您需要编写:

You can create a HTML anchor with htmltools::a().
In order to create a link to slide #2, you need to write:

htmltools::a("text", href = "javascript:slidedeck.loadSlide(2)")

您可以轻松地矢量化此表达式.不要忘记将结果列表传递给 htmltools :: tagList().
这是问题中引用的示例的最小Rmd:

You can easily vectorize this expression. Don't forget to pass the resulting list to htmltools::tagList().
Here's a minimal Rmd with the example referenced in the question:

---
title: "Presentation"
output: ioslides_presentation
---

## Slide 1 - page 2

This is the first slide. With links to other slides:

```{r echo=FALSE}
input <- data.frame(text = c("a", "b", "c"),
                    page_number = c(3, 5, 6))

htmltools::tagList(
  mapply(
    htmltools::a,
    input$text,
    href = sprintf("javascript:slidedeck.loadSlide(%i)", input$page_number),
    SIMPLIFY = FALSE)
)
```
\

If you prefer the tidyverse:

```{r echo=FALSE, message=FALSE}
library(tidyverse)

tribble(
  ~text, ~page_number,
  "a",   3,
  "b",   5,
  "c",   6
) %>%
  transmute(
    text,
    href = str_glue("javascript:slidedeck.loadSlide({page_number})")
  ) %>%
  pmap(~ htmltools::a(.x, href = .y)) %>%
  htmltools::tagList()
```

## Slide 2 - page 3

Text for slide 2

## Slide 3 - page 4

Text for slide 3

## Slide 4 - page 5

Text for slide 4

## Slide 5 - page 6

Text for slide 4

这篇关于如何在RMarkdown的代码块中使用JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 06:24