Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I place go-template actions with multi-line output at any indentation level?

Tags:

go-templates

We're creating yaml using go-templates. In them, we have actions with multi-line output that need to be indented at specific indent level. We can use the indent function for this, but it doesn't treat the first line differently and therefor requires the action definition have no indentation level.

For example:

foo:
  bar:
    baz:
{{ myYamlOutputtingAction | indent 6 }} # <-- notice 0 indent level

Is there a way I can place my action definitions at an indentation level that makes sense for the context of the template?

like image 329
Terence Avatar asked Sep 06 '17 03:09

Terence


1 Answers

UPDATE: sprig 2.13.0+

Just nindent instead of indent. The sprig library includes this function for exactly this use case.

The same code from above can be written as:

foo:
  bar:
    baz:
      {{ myYamlOutputtingAction | nindent 6 }}

Old answer for sprig versions before 2.13.0

You can change this:

foo:
  bar:
    baz:
{{ myYamlOutputtingAction | indent 6 }} # <-- notice 0 indent level

To this:

foo:
  bar:
    baz:
      {{- "\n"}}{{ myYamlOutputtingAction | indent 6 }} # <-- properly indented with a little bit fluff

A little explanation

This works by ensuring whatever content follows the {{- "\n"}} has 0 indentation. This means you can trade a hacky {{- "\n"}} for proper indentation whenever it makes sense. We generally think it's worth it.

like image 94
Terence Avatar answered Nov 13 '22 12:11

Terence