hugo/docs/content/en/functions/go-template/with.md
Bjørn Erik Pedersen 5fd1e74903
Merge commit '9b0050e9aabe4be65c78ccf292a348f309d50ccd' as 'docs'
```
git subtree add --prefix=docs/ https://github.com/gohugoio/hugoDocs.git master --squash
```

Closes #11925
2024-01-27 10:48:57 +01:00

1.9 KiB

title description categories keywords action aliases toc
with Binds context (the dot) to the expression and executes the block if expression is truthy.
aliases related returnType signatures
functions/go-template/if
functions/go-template/else
functions/go-template/end
functions/collections/IsSet
with EXPR
/functions/with
true

{{% include "functions/go-template/_common/truthy-falsy.md" %}}

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

Use with the else statement:

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

Initialize a variable, scoped to the current block:

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

Understanding context

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.

{{% note %}} Use the $ to get the context passed into the template. {{% /note %}}

This template will render the page title as desired:

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

{{% note %}} Gaining a thorough understanding of context is critical for anyone writing template code. {{% /note %}}

{{% include "functions/go-template/_common/text-template.md" %}}