github.com/fighterlyt/hugo@v0.47.1/tpl/tplimpl/templateFuncster.go (about) 1 // Copyright 2017-present 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 tplimpl 15 16 import ( 17 "fmt" 18 "html/template" 19 "strings" 20 texttemplate "text/template" 21 22 bp "github.com/gohugoio/hugo/bufferpool" 23 "github.com/gohugoio/hugo/deps" 24 ) 25 26 // Some of the template funcs are'nt entirely stateless. 27 type templateFuncster struct { 28 funcMap template.FuncMap 29 30 *deps.Deps 31 } 32 33 func newTemplateFuncster(deps *deps.Deps) *templateFuncster { 34 return &templateFuncster{ 35 Deps: deps, 36 } 37 } 38 39 // Partial executes the named partial and returns either a string, 40 // when called from text/template, for or a template.HTML. 41 func (t *templateFuncster) partial(name string, contextList ...interface{}) (interface{}, error) { 42 if strings.HasPrefix("partials/", name) { 43 name = name[8:] 44 } 45 var context interface{} 46 47 if len(contextList) == 0 { 48 context = nil 49 } else { 50 context = contextList[0] 51 } 52 53 for _, n := range []string{"partials/" + name, "theme/partials/" + name} { 54 templ, found := t.Tmpl.Lookup(n) 55 if !found { 56 // For legacy reasons. 57 templ, found = t.Tmpl.Lookup(n + ".html") 58 } 59 if found { 60 b := bp.GetBuffer() 61 defer bp.PutBuffer(b) 62 63 if err := templ.Execute(b, context); err != nil { 64 return "", err 65 } 66 67 if _, ok := templ.(*texttemplate.Template); ok { 68 return b.String(), nil 69 } 70 71 return template.HTML(b.String()), nil 72 73 } 74 } 75 76 return "", fmt.Errorf("Partial %q not found", name) 77 }