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 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件