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. 15package templates 16 17import ( 18 "github.com/gohugoio/hugo/helpers" 19 "github.com/gohugoio/hugo/resources" 20 "github.com/gohugoio/hugo/resources/internal" 21 "github.com/gohugoio/hugo/resources/resource" 22 "github.com/gohugoio/hugo/tpl" 23 "github.com/pkg/errors" 24) 25 26// Client contains methods to perform template processing of Resource objects. 27type Client struct { 28 rs *resources.Spec 29 t tpl.TemplatesProvider 30} 31 32// New creates a new Client with the given specification. 33func New(rs *resources.Spec, t tpl.TemplatesProvider) *Client { 34 if rs == nil { 35 panic("must provice a resource Spec") 36 } 37 if t == nil { 38 panic("must provide a template provider") 39 } 40 return &Client{rs: rs, t: t} 41} 42 43type executeAsTemplateTransform struct { 44 rs *resources.Spec 45 t tpl.TemplatesProvider 46 targetPath string 47 data interface{} 48} 49 50func (t *executeAsTemplateTransform) Key() internal.ResourceTransformationKey { 51 return internal.NewResourceTransformationKey("execute-as-template", t.targetPath) 52} 53 54func (t *executeAsTemplateTransform) Transform(ctx *resources.ResourceTransformationCtx) error { 55 tplStr := helpers.ReaderToString(ctx.From) 56 templ, err := t.t.TextTmpl().Parse(ctx.InPath, tplStr) 57 if err != nil { 58 return errors.Wrapf(err, "failed to parse Resource %q as Template:", ctx.InPath) 59 } 60 61 ctx.OutPath = t.targetPath 62 63 return t.t.Tmpl().Execute(templ, ctx.To, t.data) 64} 65 66func (c *Client) ExecuteAsTemplate(res resources.ResourceTransformer, targetPath string, data interface{}) (resource.Resource, error) { 67 return res.Transform(&executeAsTemplateTransform{ 68 rs: c.rs, 69 targetPath: helpers.ToSlashTrimLeading(targetPath), 70 t: c.t, 71 data: data, 72 }) 73} 74