HUGO
Menu
GitHub 90577 stars Mastodon

with

Binds context (the dot) to the expression and executes the block if the expression is truthy.
Syntax
with EXPR

Usage

The with statement binds the context (the dot) to the expression and executes the block if the expression is truthy. Use the else statement to execute an alternate block if the expression is falsy, and else with to check multiple conditions.

The falsy values are false, 0, any nil pointer or interface value, any array, slice, map, or string of length zero, and zero time.Time values.

Everything else is truthy.

Within the block, the context is the value of the expression, not the context passed into the template. For example, at the top of a page template, the context is a Page object, but within a with block that receives an integer, the context is an integer. Use the $ to access the template context from within the block.

To assign the value of the expression to a variable, use the with $var := EXPR form. The variable is scoped to the block.

To write effective templates, you must understand how context works.

See Go’s text/template documentation for more information.

Examples

{{ $var := "foo" }}
{{ with $var }}
  {{ . }} → foo
{{ end }}

With an else statement:

{{ $var := "foo" }}
{{ with $var }}
  {{ . }} → foo
{{ else }}
  {{ print "var is falsy" }}
{{ end }}

Checking multiple conditions with else with:

{{ $v1 := 0 }}
{{ $v2 := 42 }}
{{ with $v1 }}
  {{ . }}
{{ else with $v2 }}
  {{ . }} → 42
{{ else }}
  {{ print "v1 and v2 are falsy" }}
{{ end }}

Assigning the value to a variable scoped to the block:

{{ with $var := 42 }}
  {{ . }} → 42
  {{ $var }} → 42
{{ end }}
{{ $var }} → undefined

Accessing the template context from within the block:

{{ with 42 }}
  {{ $.Title }}
{{ end }}