HUGO
Menu
GitHub 87548 stars Mastodon

with

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

Syntax

with EXPR

假值包括 false0、任何 nil 指针或接口值、任何长度为零的数组、切片、映射或字符串,以及零值 time.Time

其他所有值都是真值。

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

Use with the else statement:

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

Use else with to check multiple conditions:

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

Initialize a variable, scoped to the current block:

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

Understanding context

See the context section in the introduction to templating.

For example, at the top of a page template, the context (the dot) is a Page object. Inside of the with block, the context is bound to the value passed to the with statement.

With this contrived example:

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

Hugo will throw an error:

can't evaluate field Title in type int

The error occurs because we are trying to use the .Title method on an integer instead of a Page object. Inside of the with block, if we want to render the page title, we need to get the context passed into the template.

Use the $ to get the context passed into the template.

This template will render the page title as desired:

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

Gaining a thorough understanding of context is critical for anyone writing template code.

有关更多信息,请参阅 Go 的 text/template 文档。


Last updated: January 1, 0001
Improve this page