Substringing in go templates?

agolangf · · 647 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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&#39;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 &#34;function &#34;shortID&#34; not defined&#34;</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{ &#34;shortID&#34;: func(s string) string { return &#34;...&#34; + s[len(s)-10:] }, } templateManager.Init(&#34;templates/includes/*.html&#34;, &#34;templates/layouts/*.html&#34;, funcMap) </code></pre></pre>twek: <pre><p>Well I got it working,</p> <pre><code>t.templates[templateName] = template.Must(template.New(&#34;&#34;).Funcs(funcMap).ParseFiles(files...)) </code></pre> <p>I&#39;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&#39;s name is <code>&#34;&#34;</code></p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

647 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传