如何在Quarto网站中添加Google Tag Manager代码片段?
在Quarto网站中添加Google Tag Manager(GTM)代码
方法一:使用Quarto的includes配置(推荐)
Quarto支持通过项目配置文件直接指定代码插入位置,无需修改核心模板,操作步骤如下:
创建代码片段文件
- 在网站项目根目录新建
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) -->
- 在网站项目根目录新建
修改
_quarto.yml配置
在网站配置块中添加includes节点,指定代码插入位置:website: title: "你的网站标题" # 保留原有其他配置 includes: in_header: includes/gtm-head.html before_body: includes/gtm-body.html重新渲染网站
执行命令quarto render,GTM代码会自动插入到对应位置。
方法二:自定义HTML模板(灵活扩展用)
若需要更精细化的页面控制,可通过自定义模板实现:
导出默认模板
执行命令将Quarto默认HTML模板导出到项目目录:quarto template copy quarto-html .目录下会生成
_template.html文件。插入GTM代码
打开_template.html,找到<head>标签,将GTM的<script>代码插入其中;找到<body>标签的起始位置,插入GTM的<noscript>代码。配置使用自定义模板
在_quarto.yml中指定模板路径:website: title: "你的网站标题" # 保留原有其他配置 format: html: template: _template.html重新渲染网站
执行quarto render完成配置生效。
注意:将上述代码中的GTM-XXXXXXX替换为你实际的GTM容器ID。
内容的提问来源于stack exchange,提问作者Wlademir Ribeiro Prates
相关产品推荐
相关产品推荐

