Question: How can I get the raw text of a template?

xuanbao · · 367 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I scanned a bunch of templates that were under a folder using:</p> <p><code>t = template.ParseGlob(&#34;templates/*.tmpl&#34;)</code></p> <p>Now I would like to write the raw text of those templates in a .go file. (I do not mean to execute them.) Imagine something like:</p> <pre><code>const ( template1 = `file 1 raw text` template2 = `file 2 raw text` ) </code></pre> <p>I tried with:</p> <p><code>t.Lookup(&#34;templateName.tmpl&#34;).Tree.text</code></p> <p>But the <code>text</code> field is unexported. I cannot find a way to access the raw text but I might be missing something totally obvious here.</p> <p>If it cannot be done, the alternative is to just scan the template files myself but the fact that <code>html/template</code> places the templates in a tree saves tons of work, so I thought I&#39;d ask first.</p> <p>P.S. I am already aware of libraries like go-bindata</p> <hr/>**评论:**<br/><br/>blueblank: <pre><p>pseudo code:</p> <p>create a new bytes buffer</p> <p>execute the template into the buffer</p> <p>dump the buffer where you need it</p> <p>But that still not going to get you the exact raw text of the template, i.e. I&#39;m assuming you want the actual template code, and since all the Template struct is private and you&#39;re stuck to methods, there isn&#39;t much else I can think of -- there probably something with reflect and/or unsafe you could do but more trouble than benefit. The way standard templates work assumes you have control over the template code to start...so the easiest most go way I can think is just copy/paste. If you have thousands of templates its still sort of a data munging exercise you can write a script to read a file and output the data to another file. </p></pre>

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

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