Skip to content
This repository has been archived by the owner on Jul 11, 2023. It is now read-only.

Eun/yaegi-template

Repository files navigation

yaegi-template Actions Status Coverage Status PkgGoDev GoDoc go-report

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",
    })
}

Example #2

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",
	})
}