# Format

```ts
import { formatTemplate } from '@memomori/obol/format'

formatTemplate('{{range $i,$u:=.users}}{{$u.name|upper}}{{end}}')
// {{ range $i, $u := .users }}{{ $u.name | upper }}{{ end }}
```

`formatTemplate(text, options)` lays out `text` by fixed rules. It changes
only whitespace that never reaches the output, so the result parses to the
same tree and prints the same text as the source.

## What it changes

- One space inside each delimiter: `{{ .name }}` and `{{- .name -}}`.
- One space around `|`, `:=` and `=`, and after a comma.
- No space just inside parentheses: `(len .items)`.
- Indentation, but only in whitespace a trim marker removes. Where `{{-` or
  `-}}` removes a line break, the next line sits two spaces in from the line
  that opened its block, and `{{ else }}` and `{{ end }}` line up with that
  line. At most one blank line stays there:

```gotmpl
{{- range .items -}}
  {{- if .done }}
    <s>{{ .name }}</s>
  {{- end }}
{{- end }}
```

## What it keeps

- Text outside actions, unless a trim marker removes it, so an indent the
  output prints stays as written.
- Whether two operands touch. `(.x).y` reads a field of the result, and
  `(.x) .y` passes two arguments, so neither gains or loses a space.
- Comments, byte for byte. Go reads `{{ /*` as an action, not a comment.
- Actions with a stray character, which Go would reject.
- Indentation outside any block, and after an `{{ end }}` with no block.

It reads the text with the lexer and does not parse it, so a fragment such as
`{{ range .items }}` with no `{{ end }}` formats too. Text the lexer rejects,
such as an unclosed action, throws a [`ParseError`](../api/errors.md).

## Delimiters

```ts
formatTemplate('[[.name|upper]]', { leftDelim: '[[', rightDelim: ']]' })
// [[ .name | upper ]]
```
