LoginSignup
1
0

More than 3 years have passed since last update.

Golangの継承(extends)対応テンプレート(goingtpl)を作ってみた

Posted at

Golangのインクルード(include)対応テンプレート(goingtpl)を作ってみた
を改良して、継承(extends)表記にも対応してみました。
そもそもGoでもテンプレートの継承的な動作はできるのですが、プログラム側で継承元ファイルを指定してあげる必要があります。(のはず。。
それをテンプレート側の記述だけで完結させ、プログラム側は自動で継承元ファイルを読み込むようになるというものです。

というのも最近はもっぱらPython(Django)を使うことが多く、そのテンプレート表記に慣れてしまっ為にGoでも同じように記述できないかなと(笑)

goingtpl

下記GitHubで公開中です。
https://github.com/playree/goingtpl
使い方などの詳細は下記
https://github.com/playree/goingtpl/blob/master/README.JP.md

テンプレートのイ継承(extends)機能

テンプレートファイルに継承元のテンプレートファイルを記述することができます。
テンプレートファイルに {{extends "xxx.html"}} のように記述します。

base.html
<!DOCTYPE html>
<html><body>
  <h1>{{template "title" .}}</h1>
  <div style="background-color: #ddf;">
    {{template "content" .}}
  </div>
  <p>Footer</p>
</body></html>
page1.html
{{extends "base.html"}}
{{define "title"}}Page1{{end}}
{{define "content"}}
  <p>This is Page1.</p>
{{end}}

あとは下記のように専用のパースメソッドを使用して、テンプレートファイルをパースするだけで、extends指定したファイルも一緒にパースされます。

パースメソッド
tpl := template.Must(goingtpl.ParseFile("page1.html"))

パース後のHTMLは下記のようになります。

パース後のHTML
<!DOCTYPE html>
<html><body>
  <h1>Page1</h1>
  <div style="background-color: #ddf;">
    <p>This is Page1.</p>
  </div>
  <p>Footer</p>
</body></html>

下記はプログラムが側のサンプルです。

サンプル
package main

import (
    "fmt"
    "html/template"
    "log"
    "net/http"
    "time"

    "github.com/playree/goingtpl"
)

func main() {
    // テンプレートのディレクトリを設定
    goingtpl.SetBaseDir("./templates")

    http.HandleFunc("/test", handleTest)
    log.Fatal(http.ListenAndServe(":8088", nil))
}

func handleTest(w http.ResponseWriter, r *http.Request) {
    start := time.Now().UnixNano()

    // page1.htmlをパース
    tpl := template.Must(goingtpl.ParseFile("page1.html"))
    tpl.Execute(w, nil)

    fmt.Printf("ExecTime=%d MicroSec\n",
        (time.Now().UnixNano()-start)/int64(time.Microsecond))
}

実行結果はこんな感じ。
base.htmlの内容もパースされているのが分かると思います。
extends.png

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0