File: tags_widthratio.go

package info (click to toggle)
golang-github-flosch-pongo2.v4 4.0.2-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bookworm-backports, trixie
  • size: 860 kB
  • sloc: makefile: 3
file content (83 lines) | stat: -rw-r--r-- 1,655 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package pongo2

import (
	"fmt"
	"math"
)

type tagWidthratioNode struct {
	position     *Token
	current, max IEvaluator
	width        IEvaluator
	ctxName      string
}

func (node *tagWidthratioNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
	current, err := node.current.Evaluate(ctx)
	if err != nil {
		return err
	}

	max, err := node.max.Evaluate(ctx)
	if err != nil {
		return err
	}

	width, err := node.width.Evaluate(ctx)
	if err != nil {
		return err
	}

	value := int(math.Ceil(current.Float()/max.Float()*width.Float() + 0.5))

	if node.ctxName == "" {
		writer.WriteString(fmt.Sprintf("%d", value))
	} else {
		ctx.Private[node.ctxName] = value
	}

	return nil
}

func tagWidthratioParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
	widthratioNode := &tagWidthratioNode{
		position: start,
	}

	current, err := arguments.ParseExpression()
	if err != nil {
		return nil, err
	}
	widthratioNode.current = current

	max, err := arguments.ParseExpression()
	if err != nil {
		return nil, err
	}
	widthratioNode.max = max

	width, err := arguments.ParseExpression()
	if err != nil {
		return nil, err
	}
	widthratioNode.width = width

	if arguments.MatchOne(TokenKeyword, "as") != nil {
		// Name follows
		nameToken := arguments.MatchType(TokenIdentifier)
		if nameToken == nil {
			return nil, arguments.Error("Expected name (identifier).", nil)
		}
		widthratioNode.ctxName = nameToken.Val
	}

	if arguments.Remaining() > 0 {
		return nil, arguments.Error("Malformed widthratio-tag arguments.", nil)
	}

	return widthratioNode, nil
}

func init() {
	RegisterTag("widthratio", tagWidthratioParser)
}