execute_as_template.go (2348B)
1 // Copyright 2018 The Hugo Authors. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 // Package templates contains functions for template processing of Resource objects. 15 package templates 16 17 import ( 18 "fmt" 19 20 "github.com/gohugoio/hugo/helpers" 21 "github.com/gohugoio/hugo/resources" 22 "github.com/gohugoio/hugo/resources/internal" 23 "github.com/gohugoio/hugo/resources/resource" 24 "github.com/gohugoio/hugo/tpl" 25 ) 26 27 // Client contains methods to perform template processing of Resource objects. 28 type Client struct { 29 rs *resources.Spec 30 t tpl.TemplatesProvider 31 } 32 33 // New creates a new Client with the given specification. 34 func New(rs *resources.Spec, t tpl.TemplatesProvider) *Client { 35 if rs == nil { 36 panic("must provice a resource Spec") 37 } 38 if t == nil { 39 panic("must provide a template provider") 40 } 41 return &Client{rs: rs, t: t} 42 } 43 44 type executeAsTemplateTransform struct { 45 rs *resources.Spec 46 t tpl.TemplatesProvider 47 targetPath string 48 data any 49 } 50 51 func (t *executeAsTemplateTransform) Key() internal.ResourceTransformationKey { 52 return internal.NewResourceTransformationKey("execute-as-template", t.targetPath) 53 } 54 55 func (t *executeAsTemplateTransform) Transform(ctx *resources.ResourceTransformationCtx) error { 56 tplStr := helpers.ReaderToString(ctx.From) 57 templ, err := t.t.TextTmpl().Parse(ctx.InPath, tplStr) 58 if err != nil { 59 return fmt.Errorf("failed to parse Resource %q as Template:: %w", ctx.InPath, err) 60 } 61 62 ctx.OutPath = t.targetPath 63 64 return t.t.Tmpl().Execute(templ, ctx.To, t.data) 65 } 66 67 func (c *Client) ExecuteAsTemplate(res resources.ResourceTransformer, targetPath string, data any) (resource.Resource, error) { 68 return res.Transform(&executeAsTemplateTransform{ 69 rs: c.rs, 70 targetPath: helpers.ToSlashTrimLeading(targetPath), 71 t: c.t, 72 data: data, 73 }) 74 }