dongyupen6269 2014-06-25 14:47
浏览 57
已采纳

使用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!

  • 写回答

1条回答 默认 最新

  • dongzhaiqiang6108 2014-06-25 19:07
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持