salix/tags.go

70 lines
1.8 KiB
Go
Raw Normal View History

2023-10-31 01:43:18 +00:00
/*
* Salix - Go templating engine
* Copyright (C) 2023 Elara Musayelyan
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
2023-10-29 01:10:17 +00:00
package salix
import (
"io"
2023-10-31 01:38:53 +00:00
"go.elara.ws/salix/ast"
2023-10-29 01:10:17 +00:00
)
// Tag represents a tag in a Salix template
2023-10-29 01:10:17 +00:00
type Tag interface {
Run(tc *TagContext, block, args []ast.Node) error
}
var globalTags = map[string]Tag{
"if": ifTag{},
"for": forTag{},
"include": includeTag{},
2023-10-31 03:07:57 +00:00
"macro": macroTag{},
2023-10-29 01:10:17 +00:00
}
// TagContext is passed to Tag implementations to allow them to control the interpreter
2023-10-29 01:10:17 +00:00
type TagContext struct {
w io.Writer
t *Template
local map[string]any
}
// Execute runs the interpreter on the given AST nodes, with the given local variables.
2023-10-29 01:10:17 +00:00
func (tc *TagContext) Execute(nodes []ast.Node, local map[string]any) error {
return tc.t.execute(tc.w, nodes, mergeMap(tc.local, local))
}
// GetValue evaluates the given AST node using the given local variables.
2023-10-29 01:10:17 +00:00
func (tc *TagContext) GetValue(node ast.Node, local map[string]any) (any, error) {
return tc.t.getValue(node, mergeMap(tc.local, local))
}
func mergeMap(a, b map[string]any) map[string]any {
out := map[string]any{}
if a != nil {
for k, v := range a {
out[k] = v
}
}
if b != nil {
for k, v := range b {
out[k] = v
}
}
return out
}