Skip to content
This repository has been archived by the owner on Apr 25, 2023. It is now read-only.

Commit

Permalink
close #19
Browse files Browse the repository at this point in the history
  • Loading branch information
Yuriy Bogdanov committed Sep 19, 2015
1 parent 2700441 commit e9010a0
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/rocker/template/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,21 @@ This template will yield:
RUN $'hello\nworld'
```

### {{ yaml *anything* }} or {{ *anything* | yaml }}
Marshals given input to YAML.

Example:
```
{{ .Env | yaml }}
```

This template will yield:
```
USER: johnsnow
DOCKER_MACHINE_NAME: dev
PATH: /usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
```

### {{ dump *anything* }}
Pretty-prints any variable. Useful for debugging.

Expand Down
10 changes: 10 additions & 0 deletions src/rocker/template/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"strings"
"text/template"

"github.com/go-yaml/yaml"
"github.com/kr/pretty"
)

Expand All @@ -54,6 +55,7 @@ func ProcessConfigTemplate(name string, reader io.Reader, vars Vars, funcs map[s
"assert": assertFn,
"json": jsonFn,
"shell": EscapeShellarg,
"yaml": yamlFn,
}
for k, f := range funcs {
funcMap[k] = f
Expand Down Expand Up @@ -166,6 +168,14 @@ func jsonFn(v interface{}) (string, error) {
return string(data), nil
}

func yamlFn(v interface{}) (string, error) {
data, err := yaml.Marshal(v)
if err != nil {
return "", err
}
return string(data), nil
}

func interfaceToInt(v interface{}) (int, error) {
switch v.(type) {
case int:
Expand Down
6 changes: 6 additions & 0 deletions src/rocker/template/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,12 @@ func TestProcessConfigTemplate_Shellarg(t *testing.T) {
assert.Equal(t, "echo 'hello world'", processTemplate(t, "echo {{ \"hello world\" | shell }}"))
}

func TestProcessConfigTemplate_Yaml(t *testing.T) {
assert.Equal(t, "key: foo: bar\n", processTemplate(t, "key: {{ .data | yaml }}"))
assert.Equal(t, "key: myval\n", processTemplate(t, "key: {{ .mykey | yaml }}"))
assert.Equal(t, "key: |-\n hello\n world\n", processTemplate(t, "key: {{ \"hello\\nworld\" | yaml }}"))
}

func processTemplate(t *testing.T, tpl string) string {
result, err := ProcessConfigTemplate("test", strings.NewReader(tpl), configTemplateVars, map[string]interface{}{})
if err != nil {
Expand Down

0 comments on commit e9010a0

Please sign in to comment.