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

如何在Quarto网站中添加Google Tag Manager代码片段?

在Quarto网站中添加Google Tag Manager(GTM)代码

方法一:使用Quarto的includes配置(推荐)

Quarto支持通过项目配置文件直接指定代码插入位置,无需修改核心模板,操作步骤如下:

  1. 创建代码片段文件

    • 在网站项目根目录新建includes文件夹(无则创建)。
    • 在该文件夹下创建两个HTML文件:
      • gtm-head.html:存放需插入<head>内的GTM代码,替换为你的容器ID:
        <!-- Google Tag Manager -->
        <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
        new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
        j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
        'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
        })(window,document,'script','dataLayer','GTM-XXXXXXX');</script>
        <!-- End Google Tag Manager -->
        
      • gtm-body.html:存放需插入<body>开头的GTM代码,替换为你的容器ID:
        <!-- Google Tag Manager (noscript) -->
        <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"
        height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
        <!-- End Google Tag Manager (noscript) -->
        
  2. 修改_quarto.yml配置
    在网站配置块中添加includes节点,指定代码插入位置:

    website:
      title: "你的网站标题"
      # 保留原有其他配置
      includes:
        in_header: includes/gtm-head.html
        before_body: includes/gtm-body.html
    
  3. 重新渲染网站
    执行命令quarto render,GTM代码会自动插入到对应位置。

方法二:自定义HTML模板(灵活扩展用)

若需要更精细化的页面控制,可通过自定义模板实现:

  1. 导出默认模板
    执行命令将Quarto默认HTML模板导出到项目目录:

    quarto template copy quarto-html .
    

    目录下会生成_template.html文件。

  2. 插入GTM代码
    打开_template.html,找到<head>标签,将GTM的<script>代码插入其中;找到<body>标签的起始位置,插入GTM的<noscript>代码。

  3. 配置使用自定义模板
    在_quarto.yml中指定模板路径:

    website:
      title: "你的网站标题"
      # 保留原有其他配置
      format:
        html:
          template: _template.html
    
  4. 重新渲染网站
    执行quarto render完成配置生效。

注意:将上述代码中的GTM-XXXXXXX替换为你实际的GTM容器ID。

内容的提问来源于stack exchange,提问作者Wlademir Ribeiro Prates

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:42:18