Expressions
String expressions
Within a templ element, expressions can be used to render strings. Content is automatically escaped using context-aware HTML encoding rules to protect against XSS and CSS injection attacks.
String literals, variables and functions that return a string can be used.
Literals
You can use Go string literals.
component.templ
package main
templ component() {
<div>{ "print this" }</div>
<div>{ `and this` }</div>
}
Output
<div>print this</div><div>and this</div>
Variables
Any Go string variable can be used, for example:
- A string function parameter.
- A field on a struct.
- A variable or constant string that is in scope.
/main.templ
package main
templ greet(prefix string, p Person) {
<div>{ prefix } { p.Name }{ exclamation }</div>
}
main.go
package main
type Person struct {
Name string
}
const exclamation = "!"
func main() {
p := Person{ Name: "John" }
component := greet("Hello", p)
component.Render(context.Background(), os.Stdout)
}
Output
<div>Hello John!</div>
Functions
Functions that return a string can also be used.
component.templ
package main
import "strings"
templ component() {
<div>{ strings.ToUpper("abc") }</div>
}
Output
<div>ABC</div>
Escaping
templ automatically escapes strings using HTML escaping rules.
component.templ
package main
templ component() {
<div>{ `</div><script>alert('hello!')</script><div>` }</div>
}
Output
<div></div><script>alert('hello!')</script><div></div>