summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorDave Henderson <dhenderson@gmail.com>2020-05-15 21:11:33 -0400
committerGitHub <noreply@github.com>2020-05-15 21:11:33 -0400
commit41fdbd6d3bea9266dabc0d27eb421ef1278d1ca6 (patch)
treed3b0a9f46a625aa44ce4ac5886647fc3407769b3 /docs
parent6bf845be1ca4d6ee0218662e0339918baf185120 (diff)
parent02c9e11c8bc77b95e96611ec72fe118658b421c6 (diff)
Merge pull request #845 from hairyhenderson/document-variable-scope-844
Document variable scope
Diffstat (limited to 'docs')
-rw-r--r--docs/content/syntax.md44
1 files changed, 44 insertions, 0 deletions
diff --git a/docs/content/syntax.md b/docs/content/syntax.md
index 0bcaf54f..53c1e32b 100644
--- a/docs/content/syntax.md
+++ b/docs/content/syntax.md
@@ -126,6 +126,50 @@ Hello, world!
Goodbye, world.
```
+Variables are declared with `:=`, and can be redefined with `=`:
+
+```
+{{ $w := "hello" }}
+{{ $w = "goodbye" }}
+```
+
+### Variable scope
+
+A variable's scope extends to the `end` action of the control structure (`if`,
+`with`, or `range`) in which it is declared, or to the end of the template if
+there is no such control structure.
+
+In other words, if a variable is initialized inside an `if` or `else` block,
+it cannot be referenced outside that block.
+
+This template will error with `undefined variable "$w"` since `$w` is only
+declared within `if`/`else` blocks:
+
+```
+{{ if 1 }}
+{{ $w := "world" }}
+{{ else }}
+{{ $w := "earth" }}
+{{ end }}
+
+Hello, {{ print $w }}!
+Goodbye, {{ print $w }}.
+```
+
+One way to approach this is to declare the variable first to an empty value:
+
+```
+{{ $w := "" }}
+{{ if 1 }}
+{{ $w = "world" }}
+{{ else }}
+{{ $w = "earth" }}
+{{ end -}}
+
+Hello, {{ print $w }}!
+Goodbye, {{ print $w }}.
+```
+
## Indexing arrays and maps
Occasionally, multi-dimensional data such as arrays (lists, slices) and maps