Added html helper for unsafe HTML rendering
/ docker (push) Successful in 1m2s Details

This commit is contained in:
Maxim Lebedev 2023-11-08 09:06:30 +06:00
parent 0c57b47a17
commit 6b1a81e8cb
Signed by: toby3d
GPG Key ID: 1F14E25B7C119FC5
1 changed files with 19 additions and 2 deletions

View File

@ -2,9 +2,11 @@ package fs
import (
"context"
"errors"
"fmt"
"html/template"
"io/fs"
"reflect"
"source.toby3d.me/toby3d/home/internal/theme"
)
@ -13,6 +15,21 @@ type fileSystemThemeRepository struct {
dir fs.FS
}
var ErrSafeHTML error = errors.New("unsupported input type for SafeHTML")
var helpers = template.FuncMap{
"safeHTML": func(v reflect.Value) (template.HTML, error) {
switch v.Kind() {
default:
return "", ErrSafeHTML
case reflect.Slice:
return template.HTML(v.Bytes()), nil
case reflect.String:
return template.HTML(v.String()), nil
}
},
}
func NewFileSystemThemeRepository(dir fs.FS) theme.Repository {
return &fileSystemThemeRepository{
dir: dir,
@ -20,9 +37,9 @@ func NewFileSystemThemeRepository(dir fs.FS) theme.Repository {
}
func (repo *fileSystemThemeRepository) Get(ctx context.Context) (*template.Template, error) {
tpl, err := template.New("").ParseFS(repo.dir, "baseof.html", "single.html")
tpl, err := template.New("").Funcs(helpers).ParseFS(repo.dir, "baseof.html", "single.html")
if err != nil {
return nil, fmt.Errorf("cannot find baseof.html: %w", err)
return nil, fmt.Errorf("cannot find baseof template: %w", err)
}
return tpl, nil