From 9d5ec5e3bc01c6174dea048e118edee579c36565 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Sat, 7 Feb 2026 23:06:23 +0900 Subject: fix(style): fix codeblock style for rouge --- .../index.html | 87 ++++++++++------------ 1 file changed, 41 insertions(+), 46 deletions(-) (limited to 'services/nuldoc/public/blog/posts/2024-08-19/go-template-access-outer-scope-pipeline-within-with-or-range/index.html') 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 5bdb0cc9..951f1c81 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,20 +90,19 @@ 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. は、現在の操作対象を表す特殊なオブジェクトである。 @@ -115,19 +114,18 @@ つまりこのテンプレートは、次のような構造をレンダリングしている (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", +
}, +
})
@@ -136,14 +134,13 @@ 今回おこないたいのは、withrange の中で、その外側で使われていたトップレベルのオブジェクトを参照することだ。

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

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

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

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

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

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