From d30dfc89bf1b673b2fdc0638766b930adaec228c Mon Sep 17 00:00:00 2001 From: nsfisis Date: Sat, 29 Mar 2025 00:47:55 +0900 Subject: feat(blog/nuldoc): migrate syntax highlighter from highlight.js to shiki.js --- .../index.html | 93 ++++++++++++---------- 1 file changed, 51 insertions(+), 42 deletions(-) (limited to 'vhosts/blog/public/posts/2024-08-19/go-template-access-outer-scope-pipeline-within-with-or-range/index.html') diff --git a/vhosts/blog/public/posts/2024-08-19/go-template-access-outer-scope-pipeline-within-with-or-range/index.html b/vhosts/blog/public/posts/2024-08-19/go-template-access-outer-scope-pipeline-within-with-or-range/index.html index 2d2c3761..aa6d2afb 100644 --- a/vhosts/blog/public/posts/2024-08-19/go-template-access-outer-scope-pipeline-within-with-or-range/index.html +++ b/vhosts/blog/public/posts/2024-08-19/go-template-access-outer-scope-pipeline-within-with-or-range/index.html @@ -14,8 +14,7 @@ 【Go】 text/template の with や range の内側から外側の "." にアクセスする|REPL: Rest-Eat-Program Loop - - +
@@ -71,19 +70,21 @@ 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. は、現在の操作対象を表す特殊なオブジェクトである。 @@ -97,18 +98,20 @@ つまりこのテンプレートは、次のような構造をレンダリングしている (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",
+    },
+})
+
@@ -117,13 +120,15 @@ 今回おこないたいのは、withrange の中で、その外側で使われていたトップレベルのオブジェクトを参照することだ。

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

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

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

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

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

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