quoid
July 17, 2020, 8:07pm
1
Is there any way to make the following code a bit more terse?
{{ $fallback := "fallbackVar" }}
{{ $a := "" }}
{{ $b := "" }}
{{ $c := "" }}
{{ $d := "" }}
{{ if eq .type "typevar" }}
{{ $a = .context.Params.a }}
{{ $b = .context.Params.b }}
{{ $c = .context.Params.c }}
{{ $d = .context.Params.d }}
{{ else }}
{{ $a = $fallback }}
{{ $b = $fallback }}
{{ $c = $fallback }}
{{ $d = $fallback }}
{{ end }}
I guess I am curious if one could init multiple empty vars in a single line and or reassign multiple variables to the same value in a single line or more terse way.
edit: I could assign initially assign $fallback
to the vars, but I kept it this way for the purposes of the demonstration (ie. to figure out if I can assign the same value to multiple vars in a single line)
No, you can not.
No, you can not.
quoid:
more terse way
Use a map instead of individual variables? It works, but it is not as clear as your original example.
content/post/post-1.md:
+++
title = "Post 1"
date = 2020-07-18T07:25:52-04:00
draft = false
a = "foo"
b = "bar"
c = "baz"
d = "quez"
+++
layouts/_default/single.html:
{{ define "main" }}
<h1>{{ .Title }}</h1>
<hr>
{{ partial "test.html" (dict "context" . "type" "typevar") }}
<hr>
{{ .Content }}
{{ end }}
layouts/partials/test.html:
{{- $type := .type -}}
{{- $context := .context -}}
{{- $fallback := "fallbackVar" -}}
{{- $vars := dict "a" "" "b" "" "c" "" "d" "" -}}
{{- range $k, $_ := $vars -}}
{{- if eq $type "typevar" -}}
{{- $vars = merge $vars (dict $k (index $context.Params $k)) -}}
{{- else -}}
{{- $vars = merge $vars (dict $k $fallback) -}}
{{- end -}}
{{- end -}}
To display the result:
{{- range $k, $v := $vars -}}
vars.{{ $k }} = {{ $v }}<br>
{{- end -}}
Result:
vars.a = foo
vars.b = bar
vars.c = baz
vars.d = quez
1 Like
quoid
July 18, 2020, 7:34pm
3
Thanks for the reply and example @jmooring . I agree that the more terse method is a bit less readable, but seeing an example of an alternative is great.
system
Closed
July 20, 2020, 7:34pm
4
This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.