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

如何在Go模板中将[]string类型图片数组输出到application/ld+json脚本中

实现方案

有两种常用的实现方式,更推荐第二种,可完全避免JSON格式错误问题:


方式1:直接在Go模板内遍历切片输出

你需要先把images切片和其他业务变量($currentUrl、$postTitle等)一起传入模板的上下文数据中,然后修改模板里image数组的部分如下:

<script type="application/ld+json">
{
    "@context": "https://schema.org",
    "@type": "NewsArticle",
    "mainEntityOfPage": {
        "@type": "WebPage",
        "@id": "{{$currentUrl}}"
    },
    "headline": "{{$postTile}}",
    "image": [
        {{range $index, $imageUrl := .Images}}
        {{if $index}},{{end}}"{{$imageUrl}}"
        {{end}}
    ]
}
</script>

逻辑说明:

  • 用range遍历传入的Images切片,同时获取下标$index和切片元素$imageUrl
  • 只有当下标不为0(也就是不是第一个元素)时,才在元素前输出逗号,避免最后出现多余的逗号导致JSON格式非法

注意:这种方式仅适用于你的图片URL确认没有双引号、反斜杠等需要JSON转义的特殊字符的场景,如果URL存在特殊字符会生成非法JSON。


方式2:后端提前序列化JSON(推荐)

这种方式由Go标准库的encoding/json包处理所有转义逻辑,生成的内容100%符合JSON规范,不会出现格式错误:

第一步:后端预处理切片

在渲染模板前,先把images切片序列化为JSON字符串:

import "encoding/json"

// 你的原有切片
images := []string{
    "abc.com/1.jpg",
    "abc.com/2.jpg",
    "abc.com/3.jpg",
    "...",
}

// 序列化为JSON数组字符串
imagesJSON, err := json.Marshal(images)
if err != nil {
    // 自行处理序列化错误
}

// 把imagesJSON、currentUrl、postTitle等变量一起传入模板上下文

第二步:模板内直接引用

修改模板里的image字段直接引用序列化后的变量即可:

<script type="application/ld+json">
{
    "@context": "https://schema.org",
    "@type": "NewsArticle",
    "mainEntityOfPage": {
        "@type": "WebPage",
        "@id": "{{$currentUrl}}"
    },
    "headline": "{{$postTile}}",
    "image": {{.ImagesJSON}}
}
</script>

不需要加额外的括号、引号,序列化后的结果本身就是完整的JSON数组格式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 18:18:02