Go でテンプレートエンジン (json template)

http://d.hatena.ne.jp/tokuhirom/20091117/1258418742 をみて。
Go に付いてくるテンプレートエンジンは json-template て奴でした。
記法は リファレンス にありますが、テストケース を眺めると雰囲気がつかみやすいかも。

こんなコードを書いて

package main
import (
	"template";
	"os";
	"io";
);
func main () {
	templateStr, _ := io.ReadFile("loop.tmpl");
	templ          := template.MustParse(string(templateStr), nil);
	params         := new(struct { title string; messages [10]string });
	params.title       = "タイトル";
	params.messages[0] = "文字列";
	params.messages[1] = "<s>HTML文字列</s>";
	templ.Execute(params, os.Stdout);
}

テンプレートを用意して

<title>{ title|html }</title>
<ul>
{.repeated section messages}
  {.section @}
  <li>{ @|html }</li>
  {.end}
{.end}
</ul>

実行結果。

<title>タイトル</title>
<ul>
  <li>文字列</li>
  <li>&lt;s&gt;HTML文字列&lt;/s&gt;</li>
</ul>

Go 組み込み型の配列が固定長なのが、微妙に使いづらい感はある (vector だと .repeatd section でループを回ってくれない)。