1
0
mirror of https://github.com/danog/liquid.git synced 2024-11-27 14:44:42 +01:00
liquid/chunks/render.go

90 lines
1.7 KiB
Go
Raw Normal View History

2017-06-26 15:36:52 +02:00
package chunks
2017-06-25 17:23:20 +02:00
2017-06-25 23:00:00 +02:00
import (
"fmt"
"io"
2017-06-26 15:33:07 +02:00
"github.com/osteele/liquid/expressions"
2017-06-25 23:00:00 +02:00
)
2017-06-25 17:23:20 +02:00
2017-06-25 22:21:31 +02:00
type Context struct {
Variables map[string]interface{}
}
2017-06-25 17:23:20 +02:00
2017-06-26 15:33:07 +02:00
func (c *Context) EvaluateExpr(expr string) (interface{}, error) {
return expressions.EvaluateExpr(expr, expressions.Context{Variables: c.Variables})
}
2017-06-25 17:23:20 +02:00
func (n *ASTSeq) Render(w io.Writer, ctx Context) error {
for _, c := range n.Children {
if err := c.Render(w, ctx); err != nil {
return err
}
}
return nil
}
func (n *ASTChunks) Render(w io.Writer, _ Context) error {
_, err := w.Write([]byte("{chunks}"))
return err
}
func (n *ASTText) Render(w io.Writer, _ Context) error {
_, err := w.Write([]byte(n.chunk.Source))
return err
}
2017-06-25 23:00:00 +02:00
func writeASTs(w io.Writer, seq []AST, ctx Context) error {
for _, n := range seq {
if err := n.Render(w, ctx); err != nil {
return err
}
}
return nil
2017-06-25 17:23:20 +02:00
}
2017-06-25 23:00:00 +02:00
func (n *ASTControlTag) Render(w io.Writer, ctx Context) error {
switch n.chunk.Tag {
2017-06-26 02:11:29 +02:00
case "if", "unless":
2017-06-26 15:33:07 +02:00
val, err := ctx.EvaluateExpr(n.chunk.Args)
2017-06-25 23:00:00 +02:00
if err != nil {
return err
}
2017-06-26 02:11:29 +02:00
if n.chunk.Tag == "unless" {
val = (val == nil || val == false)
}
2017-06-25 23:26:14 +02:00
switch val {
default:
2017-06-25 23:00:00 +02:00
return writeASTs(w, n.body, ctx)
2017-06-25 23:26:14 +02:00
case nil, false:
for _, c := range n.branches {
switch c.chunk.Tag {
case "else":
val = true
case "elsif":
2017-06-26 15:33:07 +02:00
val, err = ctx.EvaluateExpr(c.chunk.Args)
2017-06-25 23:26:14 +02:00
if err != nil {
return err
}
}
if val != nil && val != false {
return writeASTs(w, c.body, ctx)
}
}
2017-06-25 23:00:00 +02:00
}
return nil
default:
_, err := w.Write([]byte("{control}"))
return err
}
}
func (n *ASTObject) Render(w io.Writer, ctx Context) error {
2017-06-26 15:33:07 +02:00
val, err := ctx.EvaluateExpr(n.chunk.Tag)
2017-06-25 23:00:00 +02:00
if err != nil {
return err
}
_, err = w.Write([]byte(fmt.Sprint(val)))
2017-06-25 17:23:20 +02:00
return err
}