...
1 package statements
2
3 import (
4 "fmt"
5 "math"
6
7 "github.com/noirbizarre/gonja/exec"
8 "github.com/noirbizarre/gonja/nodes"
9 "github.com/noirbizarre/gonja/parser"
10 "github.com/noirbizarre/gonja/tokens"
11 )
12
13 type WidthRatioStmt struct {
14 Location *tokens.Token
15 current, max nodes.Expression
16 width nodes.Expression
17 ctxName string
18 }
19
20 func (stmt *WidthRatioStmt) Position() *tokens.Token { return stmt.Location }
21 func (stmt *WidthRatioStmt) String() string {
22 t := stmt.Position()
23 return fmt.Sprintf("WidthRatioStmt(Line=%d Col=%d)", t.Line, t.Col)
24 }
25
26 func (stmt *WidthRatioStmt) Execute(r *exec.Renderer, tag *nodes.StatementBlock) error {
27 current := r.Eval(stmt.current)
28 if current.IsError() {
29 return current
30 }
31
32 max := r.Eval(stmt.max)
33 if max.IsError() {
34 return max
35 }
36
37 width := r.Eval(stmt.width)
38 if width.IsError() {
39 return width
40 }
41
42 value := int(math.Ceil(current.Float()/max.Float()*width.Float() + 0.5))
43
44 if stmt.ctxName == "" {
45 r.WriteString(fmt.Sprintf("%d", value))
46 } else {
47 r.Ctx.Set(stmt.ctxName, value)
48 }
49
50 return nil
51 }
52
53 func widthratioParser(p *parser.Parser, args *parser.Parser) (nodes.Statement, error) {
54 stmt := &WidthRatioStmt{
55 Location: p.Current(),
56 }
57
58 current, err := args.ParseExpression()
59 if err != nil {
60 return nil, err
61 }
62 stmt.current = current
63
64 max, err := args.ParseExpression()
65 if err != nil {
66 return nil, err
67 }
68 stmt.max = max
69
70 width, err := args.ParseExpression()
71 if err != nil {
72 return nil, err
73 }
74 stmt.width = width
75
76 if args.MatchName("as") != nil {
77
78 nameToken := args.Match(tokens.Name)
79 if nameToken == nil {
80 return nil, args.Error("Expected name (identifier).", nil)
81 }
82 stmt.ctxName = nameToken.Val
83 }
84
85 if !args.End() {
86 return nil, args.Error("Malformed widthratio-tag args.", nil)
87 }
88
89 return stmt, nil
90 }
91
92 func init() {
93 All.Register("widthratio", widthratioParser)
94 }
95
View as plain text