将golang中的`template.JS`转换为字符串,以及将`template.HTML`转换为字符串。

huangapple go评论96阅读模式
英文:

golang template.JS to string and template.HTML to string

问题

我正在使用"html/template"。

如何将template.JS对象的值转换为字符串?template.HTML呢?

我有一个结构体,其中存储了一些js脚本和css代码/文件,例如:"HeaderCSS","FooterJS"。我将它们加载到模板的头部/尾部。问题是,我需要检查它们是否已加载,这样我就不会加载相同的脚本两次(每次重新加载都意味着加载一个新的脚本),因为我使用append,以便能够插入多个脚本。这样,每次刷新都会将脚本追加到现有脚本中。

我的想法是检查它们是否已经加载,以防止多次加载。我考虑使用**strings.Contains()**函数。但是我无法这样做,因为我不知道如何将templates.HTML和templates.JS转换为字符串。

有什么想法吗?

英文:

I'm using "html/template".

How do I convert the value of a template.JS object to a string? What about template.HTML?

I have a struct where I store some js scripts and css code/files, such as: "HeaderCSS", "FooterJS". I load them to the header/footer of my templates. The problem is that I need to check if they are loaded, so I won't load the same script twice (each reload means a new script load) because I'm using append, in order to be able to insert multiple scripts. In this way, each refresh will append the scripts to the existing scripts.

My idea is to check if they are allready loaded in order to prevent loading them multiple times. I was thinking about using strings.Contains() function. But I can't do that since I don't know to convert templates.HTML and templates.JS to string.

Any idea?

答案1

得分: 3

根据文档,它们是字符串。只需将其强制转换为字符串:

asStr := string(myTplJsObj)
英文:

Per the documentation, they're strings. Just type cast to string:

asStr := string(myTplJsObj)

huangapple
  • 本文由 发表于 2017年6月30日 21:24:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/44847607.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定