<p>Hey gophers, does anyone have any idea how to substring in an html template?
{{$img.ID[:10]}} throws a syntax error</p>
<p>I would rather not have to create a model that has both the substring and full ID if possible... (i need the full ID for the link but don't want to show it on the UI)
Thanks!</p>
<hr/>**评论:**<br/><br/>anoland: <pre><p>Template functions.</p>
<p>Here is one example. <a href="http://technosophos.com/2013/11/23/using-custom-template-functions-in-go.html" rel="nofollow">http://technosophos.com/2013/11/23/using-custom-template-functions-in-go.html</a></p></pre>twek: <pre><p>Thanks! But I cant seem to get this to work...
Could I get a little more help?
The error I get is "function "shortID" not defined"</p>
<pre><code>func (t *TemplateManager) Init(includesGlob string, layoutGlob string, funcMap template.FuncMap) {
t.templates = make(map[string]*template.Template)
layouts, _ := filepath.Glob(layoutGlob)
includes, _ := filepath.Glob(includesGlob)
for _, layout := range layouts {
files := append(includes, layout)
templateName := filepath.Base(layout)
t.templates[templateName] = template.Must(template.ParseFiles(files...)).Funcs(funcMap)
}
}
funcMap := template.FuncMap{
"shortID": func(s string) string {
return "..." + s[len(s)-10:]
},
}
templateManager.Init("templates/includes/*.html", "templates/layouts/*.html", funcMap)
</code></pre></pre>twek: <pre><p>Well I got it working,</p>
<pre><code>t.templates[templateName] = template.Must(template.New("").Funcs(funcMap).ParseFiles(files...))
</code></pre>
<p>I'm not sure why that works but </p>
<pre><code>template.Must(template.ParseFiles(files...)).Funcs(funcMap)
</code></pre>
<p>does not...</p></pre>anoland: <pre><p>Template.new() is required, even if it's name is <code>""</code></p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传