模板中带引号的字符串 [英] Quoted string in templates
问题描述
我想用电子邮件将HTML模板(实际上是JavaScript部分)放入null或字符串:
I want to put in my html template (actually JavaScript part) null or string with email:
var email = null;
// or a string:
var email = "somebody@somewhere.com";
但是带有模板
var email = {{.Email}};
我每次都会得到带引号的字符串:
I get quoted string everytime:
var email = "null";
var email = "somebody@somewhere.com";
如何解决?
这是我的代码: http://play.golang.org/p/8k4s8dv2PE
您可以看到Go用引号将字符串引起来并删除注释-进行了预处理或后处理.
You can see Go surrounds string with quotes and removes comment - there is pre or post processing.
推荐答案
Without seeing your code, the best I can do is provide an example that shows your required functionality.
如果我不得不猜测,我会说您传递的数据是一个字符串,而不是字符串指针.字符串的值不能为nil/null,只有字符串指针可以.尽管这将产生一个",而不是一个空"(如此处所示, ),所以我只能想象这是您在代码中所做的事情.
If I had to take a guess, I'd say the data you were passing in was a string, not a string pointer. A string cannot have a value of nil/null, only a string pointer can. Though that would yield a "", not a "null", (as demonstrated here), so I can only imagine that this is something weird you're doing in your code.
为防止链接腐烂,我重复了以下代码示例,尽管值得单击链接以查看其输出.
To prevent link-rot, I've duplicated the code examples below, though it's worth clicking through the links to see their output.
必需的功能:
package main
import (
"log"
"os"
"html/template"
)
type TemplateData struct {
Email *string
}
func main() {
const temp = "<script>var email = {{.Email}};</script>\n"
t := template.Must(template.New("email_template").Parse(temp))
email := "somebody@somewhere.com"
err := t.Execute(os.Stdout, TemplateData{
Email: &email,
})
if err != nil {
log.Println("executing template:", err)
}
err = t.Execute(os.Stdout, TemplateData{
Email: nil,
})
if err != nil {
log.Println("executing template:", err)
}
}
尝试使用空"字符串:
package main
import (
"log"
"os"
"html/template"
)
type TemplateData struct {
Email string
}
func main() {
const temp = "<script>var email = {{.Email}};</script>\n"
t := template.Must(template.New("email_template").Parse(temp))
email := "somebody@somewhere.com"
err := t.Execute(os.Stdout, TemplateData{
Email: email,
})
if err != nil {
log.Println("executing template:", err)
}
err = t.Execute(os.Stdout, TemplateData{
})
if err != nil {
log.Println("executing template:", err)
}
}
这篇关于模板中带引号的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!