I want to generate go template with loop which looks like following
target1:
echo from target2
target2:
echo from target2
targetN:
echo from targetN
This simply creates a target and line after
it prints from which target it's called.
I've tried with the following which works partially, any Idea what I miss here ? or how can I simplify the code in t.Execute
https://play.golang.org/p/iLWQANobKUL
package main
import (
"bytes"
"fmt"
"html/template"
)
func main() {
t := template.Must(template.New("").Parse(` {{- range .}} {{.Name}}:{{end}}
{{- range .}}
{{.Name}}:
{{"\t"}}echo from {{.Name}} {{.Text}}
{{end}}
`))
var buf bytes.Buffer
t.Execute(&buf, []interface{}{map[string]string{"Name": "target1", "Text": "echo"}})
fmt.Printf("%q\n", buf.String())
}
Is this what you need?
package main
import (
"text/template"
"os"
)
func main() {
t := template.Must(template.New("").Parse(`{{- range .}}{{.}}:
echo from {{.}}
{{end}}
`))
t.Execute(os.Stdout, []string{"target1", "target2", "target3"})
}
Output:
target1:
echo from target1
target2:
echo from target2
target3:
echo from target3
Ref: https://golang.org/pkg/text/template/
Update:
If you want to use the pipeline as a map and want to use value from the value of the corresponding key, then:
package main
import (
"text/template"
"os"
)
func main() {
t := template.Must(template.New("").Parse(`{{- range $key, $val := .}}{{$key}}:
echo from {{$val}}
{{end -}}
`))
t.Execute(os.Stdout, map[string]string{"target1": "foo1", "target2": "bar2", "target3": "baz"})
}
Output:
target1:
echo from foo1
target2:
echo from bar2
target3:
echo from baz
Related
I am using go-lang templates to output some HTML. There is a block of HTML that I will like to repeat many times. So I am using a variable to store this block of HTML. Here is a dummy version of my code:
package main
import (
"html/template"
"log"
"os"
)
var tmplString = ` // content of index.html
{{define "index"}}
{{ $DUMMY := "{{.var1}} is equal to {{.var2}}" }}
{{ $DUMMY }}
{{ $DUMMY }}
{{end}}
`
func main() {
tmpl, err := template.New("test").Parse(tmplString)
if err != nil {
log.Fatal(err)
}
varmap := map[string]interface{}{
"var1": "value",
"var2": 100,
}
tmpl.ExecuteTemplate(os.Stdout, "index", varmap)
}
The problem is that this piece of code will
{{.var1}} is equal to {{.var2}}
{{.var1}} is equal to {{.var2}}
But I need it to produce
value is equal to 100
value is equal to 100
How can I define a variable so that the string gets built from my structure?
You can concatenate strings in templates with print:
{{ $DUMMY := (print .var1 " is equal to " .var2 )}}
I am trying to simplify the template which I use to make it use a flatter data structure:
from
data := []App{App{"test data", []string{"app1", "app2", "app3"}}}
To:
data := App{App{"test data", []string{"app1", "app2", "app3"}}}
i.e. Remove the array of App, but when I try it I get an error.
Here is the working version: https://play.golang.org/p/2THGtDvlu01
I tried to change the template to
{{ range . -}}
{range $i,$a := .Command}{{if gt $i 0 }} && {{end}}{{.}}{{end}}
{{end}}
But I got an error of type mismatched, any idea how to fix it?
package main
import (
"log"
"os"
"text/template"
)
func main() {
// Define a template.
const tmpl = `
echo &1
{{range $i,$a := .Command}}{{if gt $i 0 }} && {{end}}{{.}}{{end}}
echo 2
`
// Prepare some data
type App struct {
Data string
Command []string
}
data := App{"test data", []string{"app1", "app2", "app3"}}
// Create a new template and parse into it.
t := template.Must(template.New("tmpl").Parse(tmpl))
// Execute the template with data
err := t.Execute(os.Stdout, data)
if err != nil {
log.Println("executing template:", err)
}
}
Playground example
Gives the output
echo &1
app1 && app2 && app3
echo 2
Program exited.
If you remove the []App from your code, you also need to remove the range used in the template.
Given a string (a line in a log file):
Date=2017-06-29 03:10:01.140 -700 PDT,clientDataRate="12.0,18.0,24.0,36.0,48.0,54.0",host=superawesomehost.foo,foo=bar
I'd like to replace the commas with a single space, but only within double quotes.
Desired result:
Date=2017-06-29 03:10:01.140 -700 PDT,clientDataRate="12.0 18.0 24.0 36.0 48.0 54.0",host=superawesomehost.foo,foo=bar
I've begun with a basic combination of regex and ReplaceAllString but am rapidly realizing I don't understand how to implement the match group (?) needed to accomplish this.
package main
import (
"fmt"
"log"
"regexp"
)
func main() {
logLine := "Date=2017-06-29 03:10:01.140 -700 PDT,clientDataRate=\"12.0,18.0,24.0,36.0,48.0,54.0\",host=superawesomehost.foo,foo=bar"
fmt.Println("logLine: ", logLine)
reg, err := regexp.Compile("[^A-Za-z0-9=\"-:]+")
if err != nil {
log.Fatal(err)
}
repairedLogLine := reg.ReplaceAllString(logLine, ",")
fmt.Println("repairedLogLine:", repairedLogLine )
}
All help is much appreciated.
You'll want to use Regexp.ReplaceAllStringFunc, which allows you to use a function result as the replacement of a substring:
package main
import (
"fmt"
"log"
"regexp"
"strings"
)
func main() {
logLine := `Date=2017-06-29 03:10:01.140 -700 PDT,clientDataRate="12.0,18.0,24.0,36.0,48.0,54.0",host=superawesomehost.foo,foo=bar`
fmt.Println("logLine: ", logLine)
reg, err := regexp.Compile(`"([^"]*)"`)
if err != nil {
log.Fatal(err)
}
repairedLogLine := reg.ReplaceAllStringFunc(logLine, func(entry string) string {
return strings.Replace(entry, ",", " ", -1)
})
fmt.Println("repairedLogLine:", repairedLogLine)
}
https://play.golang.org/p/BsZxcrrvaR
Does anyone know how to concatenate strings from consul for consul-template?
If I have a service 'foo' registered in Consul
{
"Node": "node1",
"Address": "192.168.0.1",
"Port": 3333
},
{
"Node": "node2",
"Address": "192.168.0.2",
"Port": 4444
}
I would like consul-template to generate the following line:
servers=192.168.0.1:3333,192.168.0.2:4444/bogus
The following attempt does not work since it leaves a trailing comma ,
servers={{range service "foo"}}{{.Address}}{{.Port}},{{end}}/bogus
# renders
servers=192.168.0.1:3333,192.168.0.2:4444,/bogus
# What I actually want
servers=192.168.0.1:3333,192.168.0.2:4444/bogus
I know consul-template uses golang template syntax, but I simply cannot figure out the syntax to get this working. Its likely that I should use consul-template's join but how do I pass both .Address and .Port to join? This is just a trivial example, and I'm not using indexes intentionally since the number of services could be more than two. Any ideas?
This should work.
{{$foo_srv := service "foo"}}
{{if $foo_srv}}
{{$last := len $foo_srv | subtract 1}}
servers=
{{- range $i := loop $last}}
{{- with index $foo_srv $i}}{{.Address}}{{.Port}},{{end}}
{{- end}}
{{- with index $foo_srv last}}{{.Address}}{{.Port}}{{end}}/bogus
{{end}}
I was thinking if "join" can be used.
Note "{{-" means removing leading white spaces (such ' ', \t, \n).
You can use a custom plugin.
servers={{service "foo" | toJSON | plugin "path/to/plugin"}}
The plugin code:
package main
import (
"encoding/json"
"fmt"
"os"
)
type InputEntry struct {
Node string
Address string
Port int
}
func main() {
arg := []byte(os.Args[1])
var input []InputEntry
if err := json.Unmarshal(arg, &input); err != nil {
fmt.Fprintln(os.Stderr, fmt.Sprintf("err: %s", err))
os.Exit(1)
}
var output string
for i, entry := range input {
output += fmt.Sprintf("%v:%v", entry.Address, entry.Port)
if i != len(input)-1 {
output += ","
}
}
fmt.Fprintln(os.Stdout, string(output))
os.Exit(0)
}
I'm trying to print the values of a map, whose keys have a dot (.) on it.
Example map:
type TemplateData struct {
Data map[string] int
}
tpldata := TemplateData{map[string]int {"core.value": 1}}
I've tried:
{{ $key := "core.value" }}
{{ .Data.key }}
but got:
2014/06/17 16:46:17 http: panic serving [::1]:41395: template: template.html:13: bad character U+0024 '$'
and
{{ .Data."core.value" }}
but got:
2014/06/17 16:45:07 http: panic serving [::1]:41393: template: template.html:12: bad character U+0022 '"'
Note that I'm able to successfully print the value of keys without dots.
As #martin-ghallager said, one needs to use an external function to access those elements.
Helpfully, the standard library already provides the index function (which does exactly what Martin's dotNotation function does).
To use it just write:
{{ index .Data "core.value" }}
The index function will return a default value in case the key is not present. This works if your dictionary has homogeneous data, however it will return the wrong value when it is heterogeneous. In such a case you can explicitly set the default with:
{{ 0 | or (index .Data "core.value") }}
As fabrizioM has stated, it's against the specs of the package, however there's nothing stopping you creating your own accessor to use dot notation using a function map:
package main
import (
"fmt"
"html/template"
"os"
)
type TemplateData struct {
Data map[string]int
}
var funcMap = template.FuncMap{
"dotNotation": dotNotation,
}
func main() {
data := TemplateData{map[string]int{"core.value": 1, "test": 100}}
t, err := template.New("foo").Funcs(funcMap).Parse(`{{dotNotation .Data "core.value"}}`)
if err != nil {
fmt.Println(err)
}
err = t.Execute(os.Stdout, data)
if err != nil {
fmt.Println(err)
}
}
func dotNotation(m map[string]int, key string) int {
// Obviously you'll need to validate existence / nil map
return m[key]
}
http://play.golang.org/p/-rlKFx3Ayt
No you can't.
According to the specs in http://golang.org/pkg/text/template/#Arguments, the key must be alphanumeric
- The name of a key of the data, which must be a map, preceded
by a period, such as
.Key
The result is the map element value indexed by the key.
Key invocations may be chained and combined with fields to any
depth:
.Field1.Key1.Field2.Key2
Although the key must be an alphanumeric identifier, unlike with
field names they do not need to start with an upper case letter.
Keys can also be evaluated on variables, including chaining:
$x.key1.key2
You can still print it by iterating over the Map
package main
import (
"fmt"
"html/template"
"os"
)
type TemplateData struct {
Data map[string]int
}
func main() {
data := TemplateData{map[string]int{"core.value": 1, "test": 100}}
t, err := template.New("foo").Parse(`{{range $key, $value := .Data}}
{{$key}}: {{$value}}
{{end}}`)
if err != nil {
fmt.Println(err)
}
err = t.Execute(os.Stdout, data)
if err != nil {
fmt.Println(err)
}
}
http://play.golang.org/p/6xB_7WQ-59
I had a similar issue where my key names in secret vault had - and . in it for example
test-key or test.key
If solved it like this
{{ with secret "secret/path/test"}}
{{ range $k, $v := .Data }}
{{ $k }}:{{ $v }}
{{ end }}
{{ end }}
Hope this will help someone...
Similarly for vault templates when exporting secrets as envvars this worked for me:
{{- with secret "secret/path/mysecret" -}}
export MYVAR="{{ index .Data.data "mykey"}}"
{{- end }}