From 4681e861efcdf9b0b73e3803e70712bc55162863 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Sat, 8 Aug 2026 10:38:18 +0900 Subject: feat(slides): improve slide controller --- .../index.html | 87 ++++++++++++---------- 1 file changed, 46 insertions(+), 41 deletions(-) (limited to 'services/nuldoc/public/blog/posts/2024-08-19/go-template-access-outer-scope-pipeline-within-with-or-range') diff --git a/services/nuldoc/public/blog/posts/2024-08-19/go-template-access-outer-scope-pipeline-within-with-or-range/index.html b/services/nuldoc/public/blog/posts/2024-08-19/go-template-access-outer-scope-pipeline-within-with-or-range/index.html index 987c0f0d..b9496c6e 100644 --- a/services/nuldoc/public/blog/posts/2024-08-19/go-template-access-outer-scope-pipeline-within-with-or-range/index.html +++ b/services/nuldoc/public/blog/posts/2024-08-19/go-template-access-outer-scope-pipeline-within-with-or-range/index.html @@ -15,7 +15,7 @@ 【Go】 text/template の with や range の内側から外側の "." にアクセスする|REPL: Rest-Eat-Program Loop - +
@@ -90,19 +90,20 @@ Go には、標準ライブラリにテンプレートライブラリ text/template がある。この text/template における制御構造、withrange は次のように使われる。

-
# {{ .Title }} -
-
# User -
-
{{ with .User }} -
{{ .Name }} ({{ .ID }}) -
{{ end }} -
-
# Items -
-
{{ range .Items }} -
- {{ . }} -
{{ end }}
+
# {{ .Title }}
+
+# User
+
+{{ with .User }}
+  {{ .Name }} ({{ .ID }})
+{{ end }}
+
+# Items
+
+{{ range .Items }}
+  - {{ . }}
+{{ end }}
+

text/template. は、現在の操作対象を表す特殊なオブジェクトである。 @@ -114,18 +115,19 @@ つまりこのテンプレートは、次のような構造をレンダリングしている (Execute() の第2引数)。

-
tmpl.Execute(out, Params{ -
Title: "foo", -
User: User{ -
ID: 123, -
Name: "john", -
}, -
Items: []string{ -
"hoge", -
"piyo", -
"fuga", -
}, -
})
+
tmpl.Execute(out, Params{
+    Title: "foo",
+    User: User{
+        ID:   123,
+        Name: "john",
+    },
+    Items: []string{
+        "hoge",
+        "piyo",
+        "fuga",
+    },
+})
+
@@ -134,13 +136,14 @@ 今回おこないたいのは、withrange の中で、その外側で使われていたトップレベルのオブジェクトを参照することだ。

-
{{ with .User }} -
ここから .Title を参照するには? -
{{ end }} -
-
{{ range .Items }} -
ここから .User を参照するには? -
{{ end }}
+
{{ with .User }}
+  ここから .Title を参照するには?
+{{ end }}
+
+{{ range .Items }}
+  ここから .User を参照するには?
+{{ end }}
+

withrange は、. を自身の対象オブジェクトに変更するので、単に {{ with .User }} の中で .Title と書いても、それは UserTitle プロパティを参照しているとみなされる。 @@ -149,7 +152,8 @@ text/template では変数が使えるので、テンプレートの先頭で

-
{{ $params := . }}
+
{{ $params := . }}
+

とでもしておけば実現は可能である。 @@ -164,13 +168,14 @@ 常にトップレベルを指す特殊変数 $ を使えばよい。

-
{{ with .User }} -
{{ $.Title }} -
{{ end }} -
-
{{ range .Items }} -
{{ $.User.Name }} -
{{ end }}
+
{{ with .User }}
+  {{ $.Title }}
+{{ end }}
+
+{{ range .Items }}
+  {{ $.User.Name }}
+{{ end }}
+

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