diff options
Diffstat (limited to 'docs/content/en/functions/go-template/with.md')
-rw-r--r-- | docs/content/en/functions/go-template/with.md | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/docs/content/en/functions/go-template/with.md b/docs/content/en/functions/go-template/with.md new file mode 100644 index 000000000..06ca38150 --- /dev/null +++ b/docs/content/en/functions/go-template/with.md @@ -0,0 +1,35 @@ +--- +title: with +description: Rebinds the context (`.`) within its scope and skips the block if the variable is absent or empty. +categories: [functions] +keywords: [] +menu: + docs: + parent: functions +function: + aliases: [] + returnType: any + signatures: [with PIPELINE] +relatedFunctions: + - with + - range +aliases: [/functions/with] +--- + +{{% readfile file="/functions/_common/go-template-functions.md" %}} + +An alternative way of writing an `if` statement and then referencing the same value is to use `with` instead. `with` rebinds the context (`.`) within its scope and skips the block if the variable is absent, unset or empty. + +The set of *empty* values is defined by [the Go templates package](https://golang.org/pkg/text/template/). Empty values include `false`, the number zero, and the empty string. + +If you want to render a block if an index or key is present in a slice, array, channel or map, regardless of whether the value is empty, you should use [`isset`](/functions/collections/isset) instead. + +The following example checks for a [user-defined site variable](/variables/site/) called `twitteruser`. If the key-value is not set, the following will render nothing: + +{{< code file="layouts/partials/twitter.html" >}} +{{ with .Site.Params.twitteruser }}<span class="twitter"> +<a href="https://twitter.com/{{ . }}" rel="author"> +<img src="/images/twitter.png" width="48" height="48" title="Twitter: {{ . }}" + alt="Twitter"></a> +</span>{{ end }} +{{< /code >}} |