/
templatefilter.go
76 lines (63 loc) 路 1.98 KB
/
templatefilter.go
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
/*
* Copyright (C) 2017 Christian Muehlhaeuser
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Christian Muehlhaeuser <muesli@gmail.com>
*/
// Package templatefilter provides a template-based filter.
package templatefilter
import (
"bytes"
"strings"
"text/template"
"github.com/muesli/beehive/filters"
"github.com/muesli/beehive/templatehelper"
)
// TemplateFilter is a template-based filter.
type TemplateFilter struct {
}
// Name returns the name of this Filter.
func (filter *TemplateFilter) Name() string {
return "template"
}
// Description returns the description of this Filter.
func (filter *TemplateFilter) Description() string {
return "This filter passes when a template-if returns true"
}
// Passes returns true when the Filter matched the data.
func (filter *TemplateFilter) Passes(data interface{}, value interface{}) bool {
switch v := value.(type) {
case string:
var res bytes.Buffer
if strings.Index(v, "{{test") >= 0 {
v = strings.Replace(v, "{{test", "{{if", -1)
v += "true{{end}}"
}
tmpl, err := template.New("_" + v).Funcs(templatehelper.FuncMap).Parse(v)
if err == nil {
err = tmpl.Execute(&res, data)
}
if err != nil {
panic(err)
}
return strings.TrimSpace(res.String()) == "true"
}
return false
}
func init() {
f := TemplateFilter{}
filters.RegisterFilter(&f)
}