Terence
Terence

Reputation: 706

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

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?

Upvotes: 5

Views: 3047

Answers (1)

Terence
Terence

Reputation: 706

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.

Upvotes: 5

Related Questions