From 41203279e88ceb19e50fc47b9781cd57afc696cc Mon Sep 17 00:00:00 2001 From: nsfisis Date: Mon, 19 Aug 2024 02:08:27 +0900 Subject: feat(blog/content): new post /posts/2024-08-19/go-template-access-outer-scope-pipeline-within-with-or-range/ --- ...-outer-scope-pipeline-within-with-or-range.ndoc | 141 +++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 vhosts/blog/content/posts/2024-08-19/go-template-access-outer-scope-pipeline-within-with-or-range.ndoc (limited to 'vhosts/blog/content/posts/2024-08-19') diff --git a/vhosts/blog/content/posts/2024-08-19/go-template-access-outer-scope-pipeline-within-with-or-range.ndoc b/vhosts/blog/content/posts/2024-08-19/go-template-access-outer-scope-pipeline-within-with-or-range.ndoc new file mode 100644 index 00000000..ee7b0ab8 --- /dev/null +++ b/vhosts/blog/content/posts/2024-08-19/go-template-access-outer-scope-pipeline-within-with-or-range.ndoc @@ -0,0 +1,141 @@ +--- +[article] +uuid = "eed112e4-3227-4b3f-9991-7e11c288ee2b" +title = "【Go】 text/template の with や range の内側から外側の \".\" にアクセスする" +description = "Go言語の text/template における with や range は \".\" を上書きする。これらの内側から外側の \".\" にアクセスする方法を調べた。" +tags = [ + "go", +] + +[[article.revisions]] +date = "2024-08-19" +remark = "公開" +--- +
+
+ TL;DR +

+ 常にトップレベルを指す特殊変数 $ を使えばよい。 +

+
+
+ はじめに +

+ Go には、標準ライブラリにテンプレートライブラリ text/template がある。 + この text/template における制御構造、withrange は次のように使われる。 +

+ + + +

+ text/template. は、現在の操作対象を表す特殊なオブジェクトである。 +

+

+ withrange は、. を変更する効果を持つ。 + with は引数に渡されたオブジェクトを . へセットして、内部のテンプレートを実行する。 + range は引数に渡されたイテレート可能なオブジェクトに対し、それぞれの要素を . へセットして、要素の個数だけ内部のテンプレートを実行する。 +

+

+ つまりこのテンプレートは、次のような構造をレンダリングしている (Execute() の第2引数)。 +

+ + + +
+
+ やりたいこと +

+ 今回おこないたいのは、withrange の中で、その外側で使われていたトップレベルのオブジェクトを参照することだ。 +

+ + + +

+ withrange は、. を自身の対象オブジェクトに変更するので、 + 単に {{ with .User }} の中で .Title と書いても、それは UserTitle プロパティを参照しているとみなされる。 +

+

+ text/template では変数が使えるので、テンプレートの先頭で +

+ + + +

+ とでもしておけば実現は可能である。 +

+

+ しかしながら、頻発するシチュエーションにしてはあまりに不恰好である。よりスマートな方法が用意されているはずだ。 +

+
+
+ 解決方法 +

+ 常にトップレベルを指す特殊変数 $ を使えばよい。 +

+ + + +

+ $ は、テンプレートが実行されるときに渡されたオブジェクトを指す。 + これを使えば現在の . に関係なくトップレベルを参照できる。 +

+

+ このことは、text/template の公式ドキュメントにも以下のように記載されている。 +

+
+ When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot. +
+
+
+ 参考 + +
+
-- cgit v1.2.3-70-g09d2