Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion infix_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ func Example_infixCalculator() {
}

// Print the expression tree.
fmt.Print(tree)
fmt.Println(tree)

txt, err := Calculate(tree)
if err != nil {
Expand All @@ -259,5 +259,6 @@ func Example_infixCalculator() {
// │ │ └── 3.2 (1:15)
// │ └── 7.6 (1:23)
// └── 2.4 (1:29)
//
// 2.4157894736842107
}
34 changes: 31 additions & 3 deletions template_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,21 @@ type tmplNode struct {
text string
}

func (n *tmplNode) String() string {
switch n.typ {
case nodeTypeSeq:
return "[]"
case nodeTypeText:
return fmt.Sprintf("%q", n.text)
case nodeTypeBranch:
return "if/else"
case nodeTypeVar:
return fmt.Sprintf("{{%s}}", n.varName)
default:
return "<Unknown>"
}
}

func lexTokenErr(err error, t *lexparse.Token) error {
return fmt.Errorf("%w: %s", err, t)
}
Expand Down Expand Up @@ -537,7 +552,7 @@ func execNode(root *lexparse.Node[*tmplNode], data map[string]string, bldr *stri
func Example_templateEngine() {
r := strings.NewReader(`Hello, {% if subject %}{{ subject }}{% else %}World{% endif %}!`)

t, err := lexparse.LexParse(
tree, err := lexparse.LexParse(
context.Background(),
lexparse.NewCustomLexer(r, lexparse.LexStateFn(lexText)),
lexparse.ParseStateFn(parseRoot),
Expand All @@ -546,12 +561,25 @@ func Example_templateEngine() {
panic(err)
}

txt, err := Execute(t, map[string]string{"subject": "世界"})
fmt.Println(tree)

txt, err := Execute(tree, map[string]string{"subject": "世界"})
if err != nil {
panic(err)
}

fmt.Print(txt)

// Output: Hello, 世界!
// Output:
// [] (0:0)
// ├── "Hello, " (1:1)
// ├── if/else (1:11)
// │ ├── {{subject}} (1:14)
// │ ├── [] (1:22)
// │ │ └── {{subject}} (1:27)
// │ └── [] (1:40)
// │ └── "World" (1:47)
// └── "!" (1:63)
//
// Hello, 世界!
}