使用HTML模板:是否可以停止模板包在脚本中的字符串周围插入引号?

All of my templates have a variable indicating the root url of their associated images. I want to output that root before the filename of the image in the body of the template, but when I do so, the templates package attempts to put quotes around it. Here's a minimal piece of code that shows my problem. IMG_ROOT is an interface in this example to better simulate the real code. The script type is text/template because its contents will be used in an underscore.js template. The type doesn't appear to matter to how it's output though.

package main

import (
    "html/template"
    "os"
)

type Data struct {
    IMG_ROOT interface{}
}

const tmpl = `
<body>
<script type="text/template">
    <img src="{{.IMG_ROOT}}/file_name.jpg"></img>
</script>
</body>

`

func main() {
    t, _ := template.New("").Parse(tmpl)
    t.Execute( os.Stdout, &Data{ template.JSStr( "/path/to/file" ) } )
}

http://play.golang.org/p/wg9JK2w2lt

If I write <img src="{{.IMG_ROOT}}/file_name.jpg"></img>, I get "\/path\/to\/file/file_name.jpg" which isn't valid.

If I write <img src={{.IMG_ROOT}}/file_name.jpg></img>, I get "/path/to/file/"file_name.jpg which doesn't work either.

Is there a workaround for this? I've tried using every 'safe' type from the templates package for the IMG_ROOT type, but haven't had any luck. I could just write a function that concatenates and returns the root and file, but it seems like there should be a simpler solution.

Any ideas?

Thanks!

You could use printf built-in function:

<img src={{printf "%s/file_name.jpg" .IMG_ROOT}}></img>

http://play.golang.org/p/2v8Q6wHu0r

But instead, I would recommend creating a custom helper function and use it to create such paths:

const ImageRoot = "path/to/files/"

func StaticFile(filename string) string {
    return ImageRoot + filename
}

func main() {
    t, _ := template.New("").Funcs(template.FuncMap{"staticFile": StaticFile}).Parse(tmpl)
    t.Execute(os.Stdout, nil)
}

And then in your templates you can just do

<img src="{{staticFile "image.jpg"}}"></img>

http://play.golang.org/p/NQTHmqNeT0