Template composition
Templates can be composed using the import expression.
templ showAll() {
@left()
@middle()
@right()
}
templ left() {
<div>Left</div>
}
templ middle() {
<div>Middle</div>
}
templ right() {
<div>Right</div>
}
Output
<div>
Left
</div>
<div>
Middle
</div>
<div>
Right
</div>
Children
Children can be passed to a component for it to wrap.
templ showAll() {
@wrapChildren() {
<div>Inserted from the top</div>
}
}
templ wrapChildren() {
<div id="wrapper">
{ children... }
</div>
}
note
The use of the { children... }
expression in the child component.
output
<div id="wrapper">
<div>
Inserted from the top
</div>
</div>
Components as parameters
Components can also be passed as parameters and rendered using the @component
expression.
package main
templ heading() {
<h1>Heading</h1>
}
templ layout(contents templ.Component) {
<div id="heading">
@heading()
</div>
<div id="contents">
@contents
</div>
}
templ paragraph(contents string) {
<p>{ contents }</p>
}
main.go
package main
import (
"context"
"os"
)
func main() {
c := paragraph("Dynamic contents")
layout(c).Render(context.Background(), os.Stdout)
}
output
<div id="heading">
<h1>Heading</h1>
</div>
<div id="contents">
<p>Dynamic contents</p>
</div>
You can pass templ
components as parameters to other components within templates using standard Go function call syntax.
package main
templ heading() {
<h1>Heading</h1>
}
templ layout(contents templ.Component) {
<div id="heading">
@heading()
</div>
<div id="contents">
@contents
</div>
}
templ paragraph(contents string) {
<p>{ contents }</p>
}
templ root() {
@layout(paragraph("Dynamic contents"))
}
main.go
package main
import (
"context"
"os"
)
func main() {
root().Render(context.Background(), os.Stdout)
}
output
<div id="heading">
<h1>Heading</h1>
</div>
<div id="contents">
<p>Dynamic contents</p>
</div>