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

Quarto网站开发:实现「显示答案」按钮模板及自动ID生成

在Quarto中实现可复用的折叠答案组件

1. 用自定义短代码实现[answer]语法+自动生成唯一ID

Quarto支持通过Lua短代码实现你要的自定义语法,同时自动生成递增的唯一ID,具体步骤如下:

步骤1:创建Lua短代码文件

在项目根目录新建_extensions/answer/answer.lua文件,写入以下代码:

local counter = 0

-- 处理包裹答案的容器
function Div(el)
  if el.classes:includes("answer-container") then
    counter = counter + 1
    local answer_id = "answer" .. counter
    -- 生成切换按钮
    local button = pandoc.RawInline("html", '<button onclick="toggleAnswer(\'' .. answer_id .. '\')" class="answer-btn">显示/隐藏答案</button>')
    -- 生成带唯一ID的答案区域
    local answer_div = pandoc.Div(el.content, {id = answer_id, class = "answer-content", style = "display: none;"})
    return pandoc.Div({button, answer_div}, {class = "answer-wrapper"})
  end
end

-- 识别[answer]和[/answer]标记
function Str(el)
  if el.text == "[answer]" then
    return pandoc.RawInline("html", '<div class="answer-container">')
  elseif el.text == "[/answer]" then
    return pandoc.RawInline("html", '</div>')
  end
end

步骤2:启用自定义扩展

在项目根目录的_quarto.yml中添加扩展配置:

extensions:
  - answer

步骤3:添加切换逻辑的JavaScript

新建或修改_includes/header.html文件,加入切换函数:

function toggleAnswer(id) {
  const answerEl = document.getElementById(id);
  answerEl.style.display = answerEl.style.display === "none" ? "block" : "none";
}

2. 使用方式

在.qmd文件中直接用你想要的语法即可,无需手动设置ID:

[answer]
这里是答案内容,支持Markdown格式,比如**加粗文本**、有序列表:
1. 第一点
2. 第二点
[/answer]

3. 自定义样式(可选)

如果需要美化组件,可在styles.css中添加样式:

.answer-btn {
  padding: 6px 12px;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}
.answer-content {
  margin-top: 10px;
  padding: 12px;
  border-left: 3px solid #007bff;
  background-color: #f8f9fa;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 15:03:30