You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R Markdown中Python代码块折叠功能失效求助

解决R Markdown中reticulate代码块折叠失效问题

问题根源是reticulate生成的Python代码块与原生R代码块的HTML类名不同,原JS选择器仅匹配R代码块,导致Python代码块无法触发折叠逻辑。以下是修正方案:

修正后的自定义JS代码

调整选择器,同时匹配R和Python代码块的类:

$(document).ready(function() {
  // 遍历所有R和Python代码块
  $('.sourceCode.r, .sourceCode.python').each(function() {
    // 创建折叠按钮
    var toggleBtn = $('<button>', {
      class: 'code-toggle',
      text: '展开代码',
      click: function() {
        // 切换代码内容显示状态
        $(this).next('.sourceCode').find('pre').toggle();
        // 切换按钮文本
        $(this).text($(this).text() === '展开代码' ? '收起代码' : '展开代码');
      }
    });
    // 初始隐藏代码内容
    $(this).find('pre').hide();
    // 将按钮插入到代码块前方
    $(this).before(toggleBtn);
  });
});

完整R Markdown示例

---
title: "代码块折叠功能测试"
output: html_document
---

```{js, echo=FALSE}
$(document).ready(function() {
  $('.sourceCode.r, .sourceCode.python').each(function() {
    var toggleBtn = $('<button>', {
      class: 'code-toggle',
      text: '展开代码',
      click: function() {
        $(this).next('.sourceCode').find('pre').toggle();
        $(this).text($(this).text() === '展开代码' ? '收起代码' : '展开代码');
      }
    });
    $(this).find('pre').hide();
    $(this).before(toggleBtn);
  });
});

R代码块(正常折叠)

# R示例代码
data <- data.frame(id = 1:5, value = rnorm(5))
summary(data)

Python代码块(reticulate,现已支持折叠)

# Python示例代码
import pandas as pd
data = pd.DataFrame({'id': range(1,6), 'value': [1.2, 3.4, 5.6, 7.8, 9.0]})
print(data.describe())
## 关键说明
- 原生R代码块的HTML类为`.sourceCode.r`,reticulate生成的Python代码块类为`.sourceCode.python`,修改选择器同时包含两者即可覆盖目标代码块。
- 若需支持其他语言代码块,只需在选择器中添加对应类名(如`.sourceCode.bash`)。

内容的提问来源于stack exchange,提问作者Andrew Lee
相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 16:30:43