Golang: Ordering map by slice in Go templates - go

I have a question about how to order a map by a slice in Go Templates and if it is possible.
Problem: I have a slice of ordered variable names that I want to display on a website, accompanying them I have a map of metadata of variable information that I would like to display together with the variable.
If I have the following struct that I pass in to the template:
type Data struct {
Variables []string
Information map[string]int
}
I would iterate over the slice and pass the variable name in to the map
{{ range $v := .Variables }} {{ index .Information $v }} {{ end }} // Doesn't work.
Here's a Go Playground with the example.
https://play.golang.org/p/AL2csnXdoU
Question: How can I do this?
I am fairly new to Golang. Thankful for any input.

The following should work. To access .Information inside range, you should use $, which is basically d in your Playground example.
{{ range .Variables }} {{ index $.Information . }} {{ end }}

Related

How do you parse brackets from path string on a variable return in Hugo?

I am writing a layout template for a Hugo generated post/page. The .yaml header is
image:
- post/mytitle/image.jpg
The template incorporates the variable in Hugo as
{{ .Params.Image }}
When served, the variable is returned as
[post/mytitle/image.jpg]
My html then becomes
<img src="[post/mytitle/image.jpg]"/>
which is 404 in the browser. I've tried a number of Hugo functions to no avail like {{ trim .Param.Image "[]" }} and {{ subset .Params.Image 1 -1 }} and {{ print .Params.Image }}. Each time Hugo returned the error: "error calling substr: unable to cast []string{"post/mytitle/image.jpg"} of type []string to string".
How do I get the variable to return the string without the brackets, or alternatively, how do I omit the brackets from the string?
In Go template, you access an item in a slice with index:
{{ index .Params.Image 0 }}
The question is why the value is a sequence in the first place. You could simply do
image:
post/mytitle/image.jpg
Then you could keep the original syntax since it is now a simple value, not a sequence.
If you want to possibly include multiple images, you'd do
{{ range .Params.Image }}<img src="{{.}}">{{ end }}
Then you can have
image:
- post/mytitle/image.jpg
- post/mytitle/anotherimage.jpg

Hugo data files from dynamic parameter

I'm developing a big hugo template. I try to simplfy the problem, so I have two datafile:
PROMO_00_1.yaml
PROMO_00_2.yaml
that are phisically stored in this directory:
themes/data/hp/
So, in the site config the user will decide which of this data file will be used simply indicate it in a param (HpElement).
In the template I call the partial in this way:
{{ partial "multiplepages/homepage/promos/00_promo_singleslide_text_video" (dict "context" . "data" $.Site.Params.HpElement) }}
In a partial I write:
{{ $data_partial := (printf "$.Site.Data.homepage.%s" .data)}}
{{ $data_partial}}
and the Hugo output is on the website:
$.Site.Data.homepage.PROMO_00_1
What I need is to access the single variable inside the .yaml file but the user MUST can decide which YAML file have to use. How can I achieve that?
Thanks
I just finished up a similar use case where I needed to select a YAML based on a date stamp. The index function is key to this operation.
https://gohugo.io/functions/index-function/
Here is a simplified version of my situation:
{{ $date := now.Format "s20060102"}}
{{ $data := (index .Site.Data.schedule $date) }}
{{ with $data }}
<h1>.longdate</h1>
{{ range .times }}
<h2>{{ .name }} - {{ .location }}
{{ end}
{{ end}
The example in the Hugo documentation uses an example where the data file is selected based on an attribute in the front matter.

How to declare a global variable in a template?

I need to write a template where I first define some variables, and then use them in what will be generated from the template:
{{ if $value.Env.CADDY_URL }}
{{ $url := $value.Env.CADDY_URL }}
{{ else }}
{{ $url := printf "http://%s.example.info" $value.Name }}
{{ end }}
{{/* more template */}}
{{/* and here I would like to use $url defined above */}}
{{ $url }}
I get the error
undefined variable "$url"
Reading the documentation, I see that
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.
Does this mean that there are no global (or scoped on the whole template) variables? Or is there a way to define $url so that it can be reused later in the template?
Variables are scoped. You create the $url variable inside the {{if}} and {{else}} blocks, so they are not visible outside of those blocks.
Create the variable before the {{if}}, and use assignment = instead of declaration :=:
{{$url := ""}}
{{ if . }}
{{ $url = "http://true.com" }}
{{ else }}
{{ $url = "http://false.com" }}
{{ end }}
{{ $url }}
Testing it:
t := template.Must(template.New("").Parse(src))
fmt.Println(t.Execute(os.Stdout, true))
fmt.Println(t.Execute(os.Stdout, false))
Output (try it on the Go Playground):
http://true.com<nil>
http://false.com<nil>
Note: Modifying template variables with assignment was added in Go 1.11, so you need to build your app with Go 1.11 or newer. If you're using an older version, you cannot modify values of template variables.
Edit: I've found a duplicate: How do I assign variables within a conditional
You can mimic "changeable template variables" in earlier versions, see this question for examples: In a Go template range loop, are variables declared outside the loop reset on each iteration?

How to set a golang variable to a template variable

I am new to golang and want to understand how to assign a template variable in golang using the golang variable.
I am using go-swagger to generate go code.
Below is the piece of a customized template to generate my swagger client.
func demo() {
{{range .Operations}}
Value := main.CheckAvail(*{{.Package}}.{{ pascalize .Name }})
{{$value := .Value}}
{{if $value }}
{{ pascalize .Name }}
{{end}}
{{end}}
}
But it gives me the error that:
" <.Value>: can't evaluate field Value in type generator.GenOperation ".
How do I assign the value to the $value? Any help?
This is not possible. The template file is a wire frame for a go file. It just generates a file of go code, which is not executed yet.
All in {{ ... }} is evaluated, when the template is parsed. At this point, all text outside the curly braces is just plain text. After the (successful) execution of the template generation the generated text will be picked up by the go compiler and compiled (if it is correct go code).
In this case you cannot evaluate Value.

How to get a field by index in template?

I send a slice of articles into template. Each articlestruct is like:
type Article struct {
ID uint32 `db:"id" bson:"id,omitempty"`
Content string `db:"content" bson:"content"`
Author string `db:"author" bson:"author"`
...
}
I can loop over articles slice in a {{range $n := articles}} and get each {{$n.Content}} but what I want is to have only the first one (outside the range loop) to use in headline.
What I tried is:
{{index .articles.Content 0}}
But I get:
Template File Error: template: articles_list.tmpl:14:33: executing
"content" at <.articles.Content>: can't evaluate field Content in type
interface {}
If I just invoke
{{index .articles 0}}
It shows the whole article[0] object.
How can I fix this?
The index function access the nth element of the specified array, so writing
{{ index .articles.Content 0 }}
is essentially trying to write articles.Content[0]
You would want something akin to
{{ with $n := index .articles 0 }}{{ $n.Content }}{{ end }}
A more concise way is:
{{(index .articles.Content 0).Content }}
Which would be the equivalent of articles[0].Content.
{{(index .articles 0).Content}}

Resources