douzhui1972 2018-01-27 15:24
浏览 45

使用golang模板填充div中的许多HTML元素?

I receive from my frontend a json with a string containing 1 or more HTML elements for example:

"textTop" : "<b>bold</b><div><i>italic</i>..."

I want to use this string to create Html elements inside a div, but I'm not really sure if I can do this with golang templates.

type FooBar struct {
    TextTop    string
}

So I'm currently storing the TextTop in a string, and then displaying it in html with:

        <div>
            {{.TextTop}}
        </div>

But of course this produces the following result in the browser. just a div containing the string, I'm passing.: enter image description here

So should I use a different type for TextTop inside Foobar struct instead of type string, which one? or can I use a golang function that reads all html elements from a string and renders them in the html as part of the DOM and not just a string?

  • 写回答

1条回答 默认 最新

  • douzhanjia0773 2018-01-27 15:32
    关注

    To prevent escaping, declare the field as type template.HTML:

    type FooBar struct {
        TextTop    template.HTML
    }
    

    See the linked documentation for information about the security risks of using template.HTML.

    评论

报告相同问题?

悬赏问题

  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型