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

按《Javascript for R》制作HTML Widget时标签转义问题求助

HTML Widget无法渲染HTML标签:转义字符导致显示异常

背景

按照《Javascript for R》相关章节操作时,无法复现最后一个示例,推测核心问题是HTML标签的<和>被转义为&lt;和&gt;,导致HTML结构无法正常解析渲染。

复现步骤

所需依赖包

library(usethis)
library(htmlwidgets)
library(shiny)

创建Widget项目

create_package("playground")
scaffoldWidget("play")

修改play.R代码

将原代码片段:

# forward options using x
  x = list(
      message = message
  )

替换为:

# forward options using x
  x = list(
      message = as.character(message)
  )

加载包并调用Widget

document(); load_all()
play(h2("Some text!"))

实际结果

实际渲染效果截图

检查页面元素发现,Widget容器的HTML内容为:

<div class="play html-widget html-fill-item-overflow-hidden html-fill-item html-widget-static-bound" id="htmlwidget-4a78c11ab194f4375219" style="width:960px;height:500px;">&lt;h2&gt;qwer&lt;/h2&gt;</div>

预期效果

将输入的h2("Some text!")渲染为格式正确的二级标题,而非显示转义后的纯文本。

疑问点

  • 转义操作发生的具体环节(是R端传递数据时自动转义?还是JavaScript渲染阶段的问题?)
  • 这种HTML转义是否属于htmlwidgets包的预期行为?
  • 书籍撰写完成后,htmlwidgets或相关工具的机制是否发生了变更?

附当前使用的play.js代码:

HTMLWidgets.widget({

  name: 'play',

  type: 'output',

  factory: function(el, width, height) {

    // TODO: define shared variables for this instance

    return {

      renderValue: function(x) {

        // TODO: code to render the widget, e.g.
        el.innerText = x.message;

      },

      resize: function(width, height) {

        // TODO: code to re-render the widget with a new size

      }

    };
  }
});

内容的提问来源于stack exchange,提问作者pietrodito

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 07:55:35