I have shortcode with a basic if/else condtional logic … and a range… but i’m getting error is … undefined variable - I don’t know why my variable is being lost
This will return related content (by tag or category)
shortcode example
{{< related taxo=tags count=3 term=hugo >}}
{{ $taxo := .Get "taxo"}}
{{ $count := .Get "count"}}
{{ $term := .Get "term"}}
{{ if eq $taxo "tags" }}
{{ $ds_related = where (index .Site.Taxonomies.tags (lower $term)).Pages "Type" "in" site.Params.mainSections }}
{{ else if eq $taxo "categories"}}
{{ $ds_related = where (index .Site.Taxonomies.categories (lower $term)).Pages "Type" "in" site.Params.mainSections }}
{{ else }}
Warning - invalid taxo
{{ end }}
<h2>What have I said about {{ humanize ($term) }}?</h2>
<ul class="list">
{{ range first $count $ds_related }}
<li class="list"><a href="{{ .Page.RelPermalink }}">{{ .Page.Title }}</a></li>
{{ end }}
</ul>
I also tried {{ with $ds_related }} but same error
A variable must be defined (with :=) before it can be assigned a value. You are attempting to assign a value to $ds_related (with =) without first defining it.
Variables defined within if, with, and range blocks are not visible outside of the block in which they are defined. You need to define the variable at the top, where you have defined $taxo, $count, and $term.
Your code didn’t work because you initialized the variable above the if-else block, then you initialized it again (twice) within the if-else block. Use := to initialize, and use = to assign value to a previously initialized variable . Syntax and scope…
{{- $var := 1 -}}
var at line 2 = {{ $var }} <br>
{{- if true -}}
var at line 5 = {{ $var }} <br>
{{- $var := 2 -}}
var at line 7 = {{ $var }} <br>
{{- end -}}
var at line 10 = {{ $var }} <br>
produces:
var at line 2 = 1
var at line 5 = 1
var at line 7 = 2
var at line 10 = 1
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. A template invocation does not inherit variables from the point of its invocation.
Additionally, you can replace your if-else block with:
Returns the result of indexing its first argument by the following arguments. Thus “index x 1 2 3” is, in Go syntax, x[1][2][3]. Each indexed item must be a map, slice, or array.