Expressions
The expressions allow for the insertion of dynamic values within a template.
An expression is written inside double braces.
{{ expression }} The expressions are always inline.
They cannot cover multiple lines or contain code blocks.
The whole content of an expression must be a valid expression of Go.
Valid expressions
GOX accepts any valid expression of Go whose result can be rendezvous within a temperate.
For example:
car := "Ford"
{{ car }}
{{ car + " Blue" }}
{{ car == "Ford" }}
{{ user }}
{{ 16 }}
{{ 10 * 5 }}
{{ strings.ToUpper(car) }} All the above expressions are valid expressions.
Invalid expressions
Not all Go expressions can be used within a template.
Expressions should always be written in a single line.
For example:
{{
strings.ToUpper(car)
}} This code is invalid because the expressions cannot cover multiple lines.
Similarly:
{{ strings.ToUpper }} The above expression returns a function, not a value that can be rendezvous within the temperate.
Or:
{{ fmt.Println(car) }} Although the call is a valid expression of Go, its result cannot be part of the renderized content.
The following types may also not be used as expressions:
These types are part of the rendering system from GOX and are documented in subsequent chapters.
Where they can be used
Expressions can be used where a temperate expects a value.
This currently includes:
- The content of an HTML tag.
- The value of an HTML attribute.
Tag content
username := "George"
return <h1>
Hello {{ username }}
</h1> More complex expressions can also be used.
return <h1>
Hello {{ strings.ToUpper(username) }}
</h1> Value of an attribute
className := "vip"
return <h1 class={{ className }}>
Hello GOX
</h1> Expressions can also combine operators and calls to functions.
return <h1 class={{ "user-" + className }}>
Hello GOX
</h1> The documentation on HTML attributes and dynamic attributes is found in the chapter of attributes.
Integration with Go
GOX does not incorporate a language of its own expression.
Expressions directly use the Go language expression system.
This means that any valid expression of Go can be used within a temperate, provided that its result can be rendezvous during the process of renderized.
Best practices
As a general recommendation:
- Keep the expressions simple and easy to read.
- Avoid complex logic within the temperate.
- Do the complex calculations before rendering when possible.