Go Evaluation

GoHT supports the evaluation of Go code within the template. This allows you to use Go to create dynamic content within the template.

Outputting Go

To output the result of Go code within the template, you use the equals = character. Following the equals, you may use any valid Go code that evaluates to a string.

= "Hello, World!"

When the generated Go code is run, it will produce the following HTML.

Hello, World!

Like plain text content, you can include the Go code on the same line after a tag.

%p= "Hello, World!"

When the generated Go code is run, it will produce the same HTML as before.

<p>Hello, World!</p>

String values only

You are limited to outputting string values in GoHT. This is a limitation borne out of the need for speed. GoHT is designed to be fast, and to parse each value using something such as fmt.Sprintf("%v", value) would slow down rendering, and it might not always output what you wanted.

If you need to output a value that is not a string, you won’t need to type out the fmt.Sprintf function. Instead, GoHT provides a shorthand way to be able to output a non-string value when you need to.

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.

%p 
  The answer is 
  =%d 42

When the generated Go code is run, it will produce the following HTML.

<p>The answer is 42</p>

See the Go docs for fmt for more information on formatting codes.

Running Go

To run Go code within the template, you use the dash - character. Following the dash, you may use any valid Go code.

%p
  - words := []string{"Hello", "World"}
  - for _, word := range words {
    %span= word
  - }

When the generated Go code is run, it will produce the following HTML.

<p>
  <span>Hello</span>
  <span>World</span>
</p>

No braces required

In the previous section a for loop was used to loop over the words slice. We could have written the same loop without the braces.

%p
  - words := []string{"Hello", "World"}
  - for _, word := range words
    %span= word

When the generated Go code is run, it will produce the same HTML as before.