Add FSTag

This commit is contained in:
Elara 2024-02-28 17:23:31 -08:00
parent c28df761d1
commit 094c48c4d1
1 changed files with 48 additions and 0 deletions

48
static_tag.go Normal file
View File

@ -0,0 +1,48 @@
package salix
import (
"io"
"io/fs"
"path"
"go.elara.ws/salix/ast"
)
// FSTag writes files from an fs.FS to a template
//
// No escaping is done on the files, so make sure to avoid user-generated data.
type FSTag struct {
// FS is the filesystem that files will be loaded from.
FS fs.FS
// PathPrefix is joined to the path string before a file is read.
PathPrefix string
// Extension is appended to the end of the path string before a file is read.
Extension string
}
func (ft FSTag) Run(tc *TagContext, block, args []ast.Node) error {
if len(args) != 1 {
return tc.PosError(tc.Tag, "expected one argument, got %d", len(args))
}
pathVal, err := tc.GetValue(args[0], nil)
if err != nil {
return err
}
pathStr, ok := pathVal.(string)
if !ok {
return tc.PosError(args[0], "expected string argument, got %T", pathVal)
}
fl, err := ft.FS.Open(path.Join(ft.PathPrefix, pathStr) + ft.Extension)
if err != nil {
return err
}
defer fl.Close()
_, err = io.Copy(tc, fl)
return err
}