Skip to content

Commit

Permalink
Merge pull request #845 from hairyhenderson/document-variable-scope-844
Browse files Browse the repository at this point in the history
Document variable scope
  • Loading branch information
Dave Henderson authored and GitHub committed May 16, 2020
2 parents 6bf845b + 02c9e11 commit 41fdbd6
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions docs/content/syntax.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 41fdbd6

Please sign in to comment.