当前位置:首页 > 文章列表 > Golang > Go问答 > 是否可以从 golang 结构返回 javascript 函数?

是否可以从 golang 结构返回 javascript 函数?

来源:stackoverflow 2024-04-24 21:45:32 0浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《是否可以从 golang 结构返回 javascript 函数?》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

下面的示例是一个 golang 结构

type column struct {
        data            string      `json:"data"`
        title           string      `json:"title"`
        type            string      `json:"type"`
        class           string      `json:"class"`
        visible         bool        `json:"visible"`
        render          template.js `json:"render"`
}

func (c *column) setvalue() {
        // code below is flexible depend on condition but here i keep it simple.
        c.render = template.js(`function(data, type, row) { if(type === 'display'){ return $.fn.datatable.render.text().display(data);} return data;}`);
}

这是 golang 模板中的 javascript

<script>
    $(function () {
        console.log({{.Columns}}, wantedobj);
    });
</script>

这里是 chrome 开发者工具。

  • 左侧列表是上面结构体中的格式值。
  • 右侧列表是我想要的格式。

渲染上有没有可能的方法来获取javascript函数而不是字符串? (请参见右图渲染


正确答案


使用 template.js 是正确的。您的问题是,在 html 模板中,值根据 contexts 进行转义:

在解析时,每个 {{.}} 都会被覆盖,以根据需要添加转义函数。