Use yaegi as a template engine.
package main
import (
"os"
"github.com/Eun/yaegi-template"
)
func main() {
template := yaegi_template.MustNew(yaegi_template.DefaultOptions(), yaegi_template.DefaultSymbols()...)
template.MustParseString(`
<html>
<$
import (
"fmt"
"time"
)
func GreetUser(name string) {
fmt.Printf("Hello %s, it is %s", name, time.Now().Format(time.Kitchen))
}
$>
<p>
<$
if context.LoggedIn {
GreetUser(context.UserName)
}
$>
</p>
</html>
`)
type Context struct {
LoggedIn bool
UserName string
}
template.MustExec(os.Stdout, &Context{
LoggedIn: true,
UserName: "Joe Doe",
})
}
You can use <$-
to strip white spaces before the code block and
-$>
to strip white spaces after the code block.
Also omitting the print statement for simple evaluations is possible.
package main
import (
"os"
"github.com/Eun/yaegi-template"
"github.com/traefik/yaegi/interp"
"github.com/traefik/yaegi/stdlib"
)
func main() {
template := yaegi_template.MustNew(interp.Options{}, stdlib.Symbols)
template.MustParseString(`
<html>
<p>
<$-
context.UserName
-$>
</html>
`)
type Context struct {
LoggedIn bool
UserName string
}
template.MustExec(os.Stdout, &Context{
LoggedIn: true,
UserName: "Joe Doe",
})
}