Formatting

You can supply formatting rules when interpolating Go and in the evaluated Go code to use non-string types. Normally, you would only be able to output string values. But if you use any of the valid formatting codes, such as %d or %02f followed by a space and then the value you wish to output, GoHT will know that you are trying to output a non-string value and will parse it accordingly.

Formatting Go Values

If you provide a formatting rule before a variable, for example, like #{rule variable}, the variable will be formatted according to the rule.

- answer := 42
%h1= "The answer is #{%d answer}"

renders as:

<h1>The answer is 42</h1>

You can also provide a formatting rule for evaluated Go code.

- answer := 42
%h1
  The answer is
  =%d answer

renders as:

<h1>
The answer is
42
</h1>

Common Formatting Rules

The Printing section of the Go docs has a list of all the formatting rules you can use. Here are a few common ones:

True/False

We can get either true or false from a boolean value by using %t. Often you will want to have a string representation of a boolean value in your HTML. Instead of adding in some Go code such as this:

- isEnabled := "true"
- if !options.Enabled
    - isEnabled = "false"
%p Option Status: #{isEnabled}

You can use the %t formatting rule to output the boolean value as a string.

%p Option Status: #{%t options.Enabled}

renders as:

<p>Option Status: true</p>

If Helper

GoHT provides a helper function to output a boolean value as a string other than “true” or “false”.

%p Option Status: #{goht.If(options.Enabled, "Enabled", "Disabled")}

renders as:

<p>Option Status: Enabled</p>

Decimal Places

You can use %f to output a floating-point number to a certain number of decimal places.

- pi := 3.14159265359
%p Pi to 2 decimal places: #{%.2f pi}

renders as:

<p>Pi to 2 decimal places: 3.14</p>

Padding

You can use %02d to pad an integer with leading zeros.

- number := 42
%p Padded number: "#{%03d number}"

renders as:

<p>Padded number: "042"</p>

You can also pad a string with spaces.

- word := "Hello"
%p Padded word: "#{%10s word}"

renders as:

<p>Padded word: "     Hello"</p>

Date and Time

You can use %v to quickly output a date or time.

- now := time.Now()
%p Current time: "#{%v now}"

renders as:

<p>Current time: "2021-01-01 12:00:00 +0000 UTC"</p>

Conclusion

Formatting Go values is a powerful feature of GoHT. It allows you to output non-string values in your HTML without having to write a lot of Go code. It also allows you to apply some simple formatting at the same time.