File: tags_if.go

package info (click to toggle)
golang-gopkg-flosch-pongo2.v3 3.0-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster
  • size: 728 kB
  • sloc: makefile: 3
file content (81 lines) | stat: -rw-r--r-- 1,766 bytes parent folder | download
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
package pongo2

import (
	"bytes"
)

type tagIfNode struct {
	conditions []IEvaluator
	wrappers   []*NodeWrapper
}

func (node *tagIfNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
	for i, condition := range node.conditions {
		result, err := condition.Evaluate(ctx)
		if err != nil {
			return err
		}

		if result.IsTrue() {
			return node.wrappers[i].Execute(ctx, buffer)
		} else {
			// Last condition?
			if len(node.conditions) == i+1 && len(node.wrappers) > i+1 {
				return node.wrappers[i+1].Execute(ctx, buffer)
			}
		}
	}
	return nil
}

func tagIfParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
	if_node := &tagIfNode{}

	// Parse first and main IF condition
	condition, err := arguments.ParseExpression()
	if err != nil {
		return nil, err
	}
	if_node.conditions = append(if_node.conditions, condition)

	if arguments.Remaining() > 0 {
		return nil, arguments.Error("If-condition is malformed.", nil)
	}

	// Check the rest
	for {
		wrapper, tag_args, err := doc.WrapUntilTag("elif", "else", "endif")
		if err != nil {
			return nil, err
		}
		if_node.wrappers = append(if_node.wrappers, wrapper)

		if wrapper.Endtag == "elif" {
			// elif can take a condition
			condition, err := tag_args.ParseExpression()
			if err != nil {
				return nil, err
			}
			if_node.conditions = append(if_node.conditions, condition)

			if tag_args.Remaining() > 0 {
				return nil, tag_args.Error("Elif-condition is malformed.", nil)
			}
		} else {
			if tag_args.Count() > 0 {
				// else/endif can't take any conditions
				return nil, tag_args.Error("Arguments not allowed here.", nil)
			}
		}

		if wrapper.Endtag == "endif" {
			break
		}
	}

	return if_node, nil
}

func init() {
	RegisterTag("if", tagIfParser)
}