From 1e2f2e68286ce018c57945ab3cdcbaaf484377ee Mon Sep 17 00:00:00 2001 From: nsfisis Date: Wed, 9 Apr 2025 20:28:28 +0900 Subject: feat(blog/content): convert from .ndoc to .dj --- ...-outer-scope-pipeline-within-with-or-range.ndoc | 141 --------------------- 1 file changed, 141 deletions(-) delete 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/go-template-access-outer-scope-pipeline-within-with-or-range.ndoc') 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 deleted file mode 100644 index ee7b0ab8..00000000 --- a/vhosts/blog/content/posts/2024-08-19/go-template-access-outer-scope-pipeline-within-with-or-range.ndoc +++ /dev/null @@ -1,141 +0,0 @@ ---- -[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