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

如何在Golang模板中使用JSON对象并为Vue应用加载数据

实现方案:Golang模板嵌入JSON数据到Vue应用

要把数据库获取的对象作为JSON直接嵌入Golang模板渲染的Vue页面,需解决数据正确序列化和Vue对JSON的识别两个核心问题,以下是修正后的完整实现:

一、后端代码修正(server.go)

补全依赖导入,将数据序列化为安全的JSON字符串后传递给模板:

package main

import (
    "encoding/json"
    "html/template"
    "io"
    "net/http"

    "github.com/labstack/echo/v4"
)

// TemplateRenderer 自定义Echo模板渲染器
type TemplateRenderer struct {
    templates *template.Template
}

// Render 实现Echo的Renderer接口
func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
    if viewContext, isMap := data.(map[string]interface{}); isMap {
        viewContext["reverse"] = c.Echo().Reverse
    }
    return t.templates.ExecuteTemplate(w, name, data)
}

func main() {
    e := echo.New()
    // 解析模板并开启自动转义确保安全
    renderer := &TemplateRenderer{
        templates: template.Must(template.ParseGlob("*.html")),
    }
    e.Renderer = renderer

    e.GET("/something", func(c echo.Context) error {
        // 模拟从数据库获取的对象(实际替换为DB查询逻辑)
        obj := map[string]string{"a": "apple", "b": "banana"}
        
        // 将对象序列化为JSON字符串,用template.JS标记为安全JS代码
        jsonData, err := json.Marshal(obj)
        if err != nil {
            return err
        }

        // 传递给模板的数据集
        templateData := map[string]interface{}{
            "embeddedData": template.JS(jsonData),
        }

        return c.Render(http.StatusOK, "template.html", templateData)
    }).Name = "foobar"

    e.Logger.Fatal(e.Start(":8000"))
}

二、前端模板修正(template.html)

提供两种常用方式让Vue识别嵌入的JSON:

方式1:全局挂载数据,组件读取

<html>
<head>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>
</head>
<body>
    <!-- 全局挂载后端传递的JSON数据 -->
    <script>
        window.embeddedData = {{ .embeddedData }};
    </script>

    <div id="app">
        <test-component :test="embeddedData"></test-component>
    </div>

    <script>
        // 注册Vue组件
        Vue.component('test-component', {
            props: ['test'],
            template: `<div>A: {{ test.a }}, B: {{ test.b }}</div>`
        });

        // 初始化Vue实例
        new Vue({
            el: '#app'
        });
    </script>
</body>
</html>

方式2:直接绑定到组件props

<html>
<head>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <!-- 直接将后端JSON作为JS对象绑定到组件props -->
        <test-component :test="{{ .embeddedData }}"></test-component>
    </div>

    <script>
        Vue.component('test-component', {
            props: ['test'],
            template: `<div>A: {{ test.a }}, B: {{ test.b }}</div>`
        });

        new Vue({
            el: '#app'
        });
    </script>
</body>
</html>

关键注意事项

  • 安全防护:用template.JS包装JSON,避免模板自动转义HTML字符,同时确保数据来自可信源,防止XSS攻击。
  • 类型匹配:后端序列化的JSON结构要与Vue组件props定义的类型一致,避免类型错误。
  • Vue版本适配:若使用Vue 3,只需调整Vue的引入和初始化方式(如使用createApp),核心逻辑不变。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:35:46