Rework template handling for function and map lookups

This is a big commit, but it deletes lots of code and simplifies a lot.

* Resolving the template funcs at execution time means we don't have to create template clones per site
* Having a custom map resolver means that we can remove the AST lower case transformation for the special lower case Params map

Not only is the above easier to reason about, it's also faster, especially if you have more than one language, as in the benchmark below:

```
name                          old time/op    new time/op    delta
SiteNew/Deep_content_tree-16    53.7ms ± 0%    48.1ms ± 2%  -10.38%  (p=0.029 n=4+4)

name                          old alloc/op   new alloc/op   delta
SiteNew/Deep_content_tree-16    41.0MB ± 0%    36.8MB ± 0%  -10.26%  (p=0.029 n=4+4)

name                          old allocs/op  new allocs/op  delta
SiteNew/Deep_content_tree-16      481k ± 0%      410k ± 0%  -14.66%  (p=0.029 n=4+4)
```

This should be even better if you also have lots of templates.

Closes #6594
This commit is contained in:
Bjørn Erik Pedersen
2019-12-10 19:56:44 +01:00
parent 167c01530b
commit a03c631c42
41 changed files with 1194 additions and 1898 deletions

View File

@@ -15,6 +15,7 @@ package hugolib
import (
"bytes"
"errors"
"fmt"
"html/template"
"io"
@@ -31,27 +32,15 @@ import (
"github.com/gohugoio/hugo/tpl"
)
const (
alias = "<!DOCTYPE html><html><head><title>{{ .Permalink }}</title><link rel=\"canonical\" href=\"{{ .Permalink }}\"/><meta name=\"robots\" content=\"noindex\"><meta charset=\"utf-8\" /><meta http-equiv=\"refresh\" content=\"0; url={{ .Permalink }}\" /></head></html>"
aliasXHtml = "<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title>{{ .Permalink }}</title><link rel=\"canonical\" href=\"{{ .Permalink }}\"/><meta name=\"robots\" content=\"noindex\"><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" /><meta http-equiv=\"refresh\" content=\"0; url={{ .Permalink }}\" /></head></html>"
)
var defaultAliasTemplates *template.Template
func init() {
//TODO(bep) consolidate
defaultAliasTemplates = template.New("")
template.Must(defaultAliasTemplates.New("alias").Parse(alias))
template.Must(defaultAliasTemplates.New("alias-xhtml").Parse(aliasXHtml))
}
type aliasHandler struct {
t tpl.TemplateFinder
t tpl.TemplateHandler
log *loggers.Logger
allowRoot bool
}
func newAliasHandler(t tpl.TemplateFinder, l *loggers.Logger, allowRoot bool) aliasHandler {
func newAliasHandler(t tpl.TemplateHandler, l *loggers.Logger, allowRoot bool) aliasHandler {
return aliasHandler{t, l, allowRoot}
}
@@ -60,33 +49,27 @@ type aliasPage struct {
page.Page
}
func (a aliasHandler) renderAlias(isXHTML bool, permalink string, p page.Page) (io.Reader, error) {
t := "alias"
if isXHTML {
t = "alias-xhtml"
}
func (a aliasHandler) renderAlias(permalink string, p page.Page) (io.Reader, error) {
var templ tpl.Template
var found bool
if a.t != nil {
templ, found = a.t.Lookup("alias.html")
}
templ, found = a.t.Lookup("alias.html")
if !found {
def := defaultAliasTemplates.Lookup(t)
if def != nil {
templ = &tpl.TemplateAdapter{Template: def}
// TODO(bep) consolidate
templ, found = a.t.Lookup("_internal/alias.html")
if !found {
return nil, errors.New("no alias template found")
}
}
data := aliasPage{
permalink,
p,
}
buffer := new(bytes.Buffer)
err := templ.Execute(buffer, data)
err := a.t.Execute(templ, buffer, data)
if err != nil {
return nil, err
}
@@ -100,8 +83,6 @@ func (s *Site) writeDestAlias(path, permalink string, outputFormat output.Format
func (s *Site) publishDestAlias(allowRoot bool, path, permalink string, outputFormat output.Format, p page.Page) (err error) {
handler := newAliasHandler(s.Tmpl, s.Log, allowRoot)
isXHTML := strings.HasSuffix(path, ".xhtml")
s.Log.DEBUG.Println("creating alias:", path, "redirecting to", permalink)
targetPath, err := handler.targetPathAlias(path)
@@ -109,7 +90,7 @@ func (s *Site) publishDestAlias(allowRoot bool, path, permalink string, outputFo
return err
}
aliasContent, err := handler.renderAlias(isXHTML, permalink, p)
aliasContent, err := handler.renderAlias(permalink, p)
if err != nil {
return err
}

View File

@@ -14,7 +14,6 @@
package hugolib
import (
"fmt"
"path/filepath"
"testing"
@@ -232,76 +231,3 @@ Page2: {{ $page2.Params.ColoR }}
"index2|Site: yellow|",
)
}
// TODO1
func TestCaseInsensitiveConfigurationForAllTemplateEngines(t *testing.T) {
t.Parallel()
noOp := func(s string) string {
return s
}
for _, config := range []struct {
suffix string
templateFixer func(s string) string
}{
//{"amber", amberFixer},
{"html", noOp},
//{"ace", noOp},
} {
doTestCaseInsensitiveConfigurationForTemplateEngine(t, config.suffix, config.templateFixer)
}
}
func doTestCaseInsensitiveConfigurationForTemplateEngine(t *testing.T, suffix string, templateFixer func(s string) string) {
c := qt.New(t)
mm := afero.NewMemMapFs()
caseMixingTestsWriteCommonSources(t, mm)
cfg, err := LoadConfigDefault(mm)
c.Assert(err, qt.IsNil)
fs := hugofs.NewFrom(mm, cfg)
th := newTestHelper(cfg, fs, t)
t.Log("Testing", suffix)
templTemplate := `
p
|
| Page Colors: {{ .Params.CoLOR }}|{{ .Params.Colors.Blue }}
| Site Colors: {{ .Site.Params.COlOR }}|{{ .Site.Params.COLORS.YELLOW }}
| {{ .Content }}
`
templ := templateFixer(templTemplate)
t.Log(templ)
writeSource(t, fs, filepath.Join("layouts", "_default", fmt.Sprintf("single.%s", suffix)), templ)
sites, err := NewHugoSites(deps.DepsCfg{Fs: fs, Cfg: cfg})
if err != nil {
t.Fatalf("Failed to create sites: %s", err)
}
err = sites.Build(BuildCfg{})
if err != nil {
t.Fatalf("Failed to build sites: %s", err)
}
th.assertFileContent(filepath.Join("public", "nn", "sect1", "page1", "index.html"),
"Page Colors: red|heavenly",
"Site Colors: green|yellow",
"Shortcode Page: red|heavenly",
"Shortcode Site: green|yellow",
)
}

View File

@@ -27,7 +27,6 @@ import (
"github.com/gohugoio/hugo/deps"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/tpl"
)
const (
@@ -334,18 +333,13 @@ func TestShortcodeTweet(t *testing.T) {
cfg.Set("privacy", this.privacy)
withTemplate := func(templ tpl.TemplateHandler) error {
templ.(tpl.TemplateTestMocker).SetFuncs(tweetFuncMap)
return nil
}
writeSource(t, fs, filepath.Join("content", "simple.md"), fmt.Sprintf(`---
title: Shorty
---
%s`, this.in))
writeSource(t, fs, filepath.Join("layouts", "_default", "single.html"), `{{ .Content }}`)
buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg, WithTemplate: withTemplate}, BuildCfg{})
buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg, OverloadedTemplateFuncs: tweetFuncMap}, BuildCfg{})
th.assertFileContentRegexp(filepath.Join("public", "simple", "index.html"), this.expected)
@@ -389,18 +383,13 @@ func TestShortcodeInstagram(t *testing.T) {
th = newTestHelper(cfg, fs, t)
)
withTemplate := func(templ tpl.TemplateHandler) error {
templ.(tpl.TemplateTestMocker).SetFuncs(instagramFuncMap)
return nil
}
writeSource(t, fs, filepath.Join("content", "simple.md"), fmt.Sprintf(`---
title: Shorty
---
%s`, this.in))
writeSource(t, fs, filepath.Join("layouts", "_default", "single.html"), `{{ .Content | safeHTML }}`)
buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg, WithTemplate: withTemplate}, BuildCfg{})
buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg, OverloadedTemplateFuncs: instagramFuncMap}, BuildCfg{})
th.assertFileContentRegexp(filepath.Join("public", "simple", "index.html"), this.expected)

View File

@@ -42,10 +42,10 @@ import (
func TestHugoModules(t *testing.T) {
t.Parallel()
if hugo.GoMinorVersion() < 12 {
if !isCI() || hugo.GoMinorVersion() < 12 {
// https://github.com/golang/go/issues/26794
// There were some concurrent issues with Go modules in < Go 12.
t.Skip("skip this for Go <= 1.11 due to a bug in Go's stdlib")
t.Skip("skip this on local host and for Go <= 1.11 due to a bug in Go's stdlib")
}
if testing.Short() {

View File

@@ -426,8 +426,8 @@ func NewHugoSites(cfg deps.DepsCfg) (*HugoSites, error) {
return newHugoSites(cfg, sites...)
}
func (s *Site) withSiteTemplates(withTemplates ...func(templ tpl.TemplateHandler) error) func(templ tpl.TemplateHandler) error {
return func(templ tpl.TemplateHandler) error {
func (s *Site) withSiteTemplates(withTemplates ...func(templ tpl.TemplateManager) error) func(templ tpl.TemplateManager) error {
return func(templ tpl.TemplateManager) error {
if err := templ.LoadTemplates(""); err != nil {
return err
}

View File

@@ -21,6 +21,27 @@ import (
qt "github.com/frankban/quicktest"
)
// The most basic build test.
func TestHello(t *testing.T) {
t.Parallel()
b := newTestSitesBuilder(t)
b.WithConfigFile("toml", `
baseURL="https://example.org"
disableKinds = ["taxonomy", "taxonomyTerm", "section", "page"]
`)
b.WithContent("p1", `
---
title: Page
---
`)
b.WithTemplates("index.html", `Site: {{ .Site.Language.Lang | upper }}`)
b.Build(BuildCfg{})
b.AssertFileContent("public/index.html", `Site: EN`)
}
func TestSmoke(t *testing.T) {
t.Parallel()

View File

@@ -480,7 +480,7 @@ func (p *pageState) Render(layout ...string) template.HTML {
templ, _ = p.s.Tmpl.Lookup(layout + ".html")
}
if templ != nil {
res, err := executeToString(templ, p)
res, err := executeToString(p.s.Tmpl, templ, p)
if err != nil {
p.s.SendError(p.wrapError(errors.Wrapf(err, ".Render: failed to execute template %q v", layout)))
return ""

View File

@@ -411,10 +411,10 @@ func (t targetPathsHolder) targetPaths() page.TargetPaths {
return t.paths
}
func executeToString(templ tpl.Template, data interface{}) (string, error) {
func executeToString(h tpl.TemplateHandler, templ tpl.Template, data interface{}) (string, error) {
b := bp.GetBuffer()
defer bp.PutBuffer(b)
if err := templ.Execute(b, data); err != nil {
if err := h.Execute(templ, b, data); err != nil {
return "", err
}
return b.String(), nil

View File

@@ -459,7 +459,7 @@ func TestPageWithDelimiterForMarkdownThatCrossesBorder(t *testing.T) {
}
cnt := content(p)
if cnt != "<p>The <a href=\"http://gohugo.io/\">best static site generator</a>.<sup id=\"fnref:1\"><a href=\"#fn:1\" class=\"footnote-ref\" role=\"doc-noteref\">1</a></sup></p>\n<section class=\"footnotes\" role=\"doc-endnotes\">\n<hr>\n<ol>\n<li id=\"fn:1\" role=\"doc-endnote\">\n<p>Many people say so. <a href=\"#fnref:1\" class=\"footnote-backref\" role=\"doc-backlink\">&#x21a9;&#xfe0e;</a></p>\n</li>\n</ol>\n</section>" {
if cnt != "<p>The <a href=\"http://gohugo.io/\">best static site generator</a>.<sup id=\"fnref:1\"><a href=\"#fn:1\" class=\"footnote-ref\" role=\"doc-noteref\">1</a></sup></p>\n<section class=\"footnotes\" role=\"doc-endnotes\">\n<hr>\n<ol>\n<li id=\"fn:1\" role=\"doc-endnote\">\n<p>Many people say so.<a href=\"#fnref:1\" class=\"footnote-backref\" role=\"doc-backlink\">&#8617;</a></p>\n</li>\n</ol>\n</section>" {
t.Fatalf("Got content:\n%q", cnt)
}
}

View File

@@ -393,7 +393,7 @@ func renderShortcode(
}
result, err := renderShortcodeWithPage(tmpl, data)
result, err := renderShortcodeWithPage(s.Tmpl, tmpl, data)
if err != nil && sc.isInline {
fe := herrors.ToFileError("html", err)
@@ -634,11 +634,11 @@ func replaceShortcodeTokens(source []byte, replacements map[string]string) ([]by
return source, nil
}
func renderShortcodeWithPage(tmpl tpl.Template, data *ShortcodeWithPage) (string, error) {
func renderShortcodeWithPage(h tpl.TemplateHandler, tmpl tpl.Template, data *ShortcodeWithPage) (string, error) {
buffer := bp.GetBuffer()
defer bp.PutBuffer(buffer)
err := tmpl.Execute(buffer, data)
err := h.Execute(tmpl, buffer, data)
if err != nil {
return "", _errors.Wrap(err, "failed to process shortcode")
}

View File

@@ -36,12 +36,12 @@ import (
qt "github.com/frankban/quicktest"
)
func CheckShortCodeMatch(t *testing.T, input, expected string, withTemplate func(templ tpl.TemplateHandler) error) {
func CheckShortCodeMatch(t *testing.T, input, expected string, withTemplate func(templ tpl.TemplateManager) error) {
t.Helper()
CheckShortCodeMatchAndError(t, input, expected, withTemplate, false)
}
func CheckShortCodeMatchAndError(t *testing.T, input, expected string, withTemplate func(templ tpl.TemplateHandler) error, expectError bool) {
func CheckShortCodeMatchAndError(t *testing.T, input, expected string, withTemplate func(templ tpl.TemplateManager) error, expectError bool) {
t.Helper()
cfg, fs := newTestCfg()
@@ -95,7 +95,7 @@ func TestNonSC(t *testing.T) {
// Issue #929
func TestHyphenatedSC(t *testing.T) {
t.Parallel()
wt := func(tem tpl.TemplateHandler) error {
wt := func(tem tpl.TemplateManager) error {
tem.AddTemplate("_internal/shortcodes/hyphenated-video.html", `Playing Video {{ .Get 0 }}`)
return nil
@@ -107,7 +107,7 @@ func TestHyphenatedSC(t *testing.T) {
// Issue #1753
func TestNoTrailingNewline(t *testing.T) {
t.Parallel()
wt := func(tem tpl.TemplateHandler) error {
wt := func(tem tpl.TemplateManager) error {
tem.AddTemplate("_internal/shortcodes/a.html", `{{ .Get 0 }}`)
return nil
}
@@ -117,7 +117,7 @@ func TestNoTrailingNewline(t *testing.T) {
func TestPositionalParamSC(t *testing.T) {
t.Parallel()
wt := func(tem tpl.TemplateHandler) error {
wt := func(tem tpl.TemplateManager) error {
tem.AddTemplate("_internal/shortcodes/video.html", `Playing Video {{ .Get 0 }}`)
return nil
}
@@ -131,7 +131,7 @@ func TestPositionalParamSC(t *testing.T) {
func TestPositionalParamIndexOutOfBounds(t *testing.T) {
t.Parallel()
wt := func(tem tpl.TemplateHandler) error {
wt := func(tem tpl.TemplateManager) error {
tem.AddTemplate("_internal/shortcodes/video.html", `Playing Video {{ with .Get 1 }}{{ . }}{{ else }}Missing{{ end }}`)
return nil
}
@@ -141,7 +141,7 @@ func TestPositionalParamIndexOutOfBounds(t *testing.T) {
// #5071
func TestShortcodeRelated(t *testing.T) {
t.Parallel()
wt := func(tem tpl.TemplateHandler) error {
wt := func(tem tpl.TemplateManager) error {
tem.AddTemplate("_internal/shortcodes/a.html", `{{ len (.Site.RegularPages.Related .Page) }}`)
return nil
}
@@ -151,7 +151,7 @@ func TestShortcodeRelated(t *testing.T) {
func TestShortcodeInnerMarkup(t *testing.T) {
t.Parallel()
wt := func(tem tpl.TemplateHandler) error {
wt := func(tem tpl.TemplateManager) error {
tem.AddTemplate("shortcodes/a.html", `<div>{{ .Inner }}</div>`)
tem.AddTemplate("shortcodes/b.html", `**Bold**: <div>{{ .Inner }}</div>`)
return nil
@@ -175,7 +175,7 @@ func TestShortcodeInnerMarkup(t *testing.T) {
func TestNamedParamSC(t *testing.T) {
t.Parallel()
wt := func(tem tpl.TemplateHandler) error {
wt := func(tem tpl.TemplateManager) error {
tem.AddTemplate("_internal/shortcodes/img.html", `<img{{ with .Get "src" }} src="{{.}}"{{end}}{{with .Get "class"}} class="{{.}}"{{end}}>`)
return nil
}
@@ -190,7 +190,7 @@ func TestNamedParamSC(t *testing.T) {
// Issue #2294
func TestNestedNamedMissingParam(t *testing.T) {
t.Parallel()
wt := func(tem tpl.TemplateHandler) error {
wt := func(tem tpl.TemplateManager) error {
tem.AddTemplate("_internal/shortcodes/acc.html", `<div class="acc">{{ .Inner }}</div>`)
tem.AddTemplate("_internal/shortcodes/div.html", `<div {{with .Get "class"}} class="{{ . }}"{{ end }}>{{ .Inner }}</div>`)
tem.AddTemplate("_internal/shortcodes/div2.html", `<div {{with .Get 0}} class="{{ . }}"{{ end }}>{{ .Inner }}</div>`)
@@ -203,7 +203,7 @@ func TestNestedNamedMissingParam(t *testing.T) {
func TestIsNamedParamsSC(t *testing.T) {
t.Parallel()
wt := func(tem tpl.TemplateHandler) error {
wt := func(tem tpl.TemplateManager) error {
tem.AddTemplate("_internal/shortcodes/bynameorposition.html", `{{ with .Get "id" }}Named: {{ . }}{{ else }}Pos: {{ .Get 0 }}{{ end }}`)
tem.AddTemplate("_internal/shortcodes/ifnamedparams.html", `<div id="{{ if .IsNamedParams }}{{ .Get "id" }}{{ else }}{{ .Get 0 }}{{end}}">`)
return nil
@@ -216,7 +216,7 @@ func TestIsNamedParamsSC(t *testing.T) {
func TestInnerSC(t *testing.T) {
t.Parallel()
wt := func(tem tpl.TemplateHandler) error {
wt := func(tem tpl.TemplateManager) error {
tem.AddTemplate("_internal/shortcodes/inside.html", `<div{{with .Get "class"}} class="{{.}}"{{end}}>{{ .Inner }}</div>`)
return nil
}
@@ -227,7 +227,7 @@ func TestInnerSC(t *testing.T) {
func TestInnerSCWithMarkdown(t *testing.T) {
t.Parallel()
wt := func(tem tpl.TemplateHandler) error {
wt := func(tem tpl.TemplateManager) error {
// Note: In Hugo 0.55 we made it so any outer {{%'s inner content was rendered as part of the surrounding
// markup. This solved lots of problems, but it also meant that this test had to be adjusted.
tem.AddTemplate("_internal/shortcodes/wrapper.html", `<div{{with .Get "class"}} class="{{.}}"{{end}}>{{ .Inner }}</div>`)
@@ -250,7 +250,7 @@ func TestEmbeddedSC(t *testing.T) {
func TestNestedSC(t *testing.T) {
t.Parallel()
wt := func(tem tpl.TemplateHandler) error {
wt := func(tem tpl.TemplateManager) error {
tem.AddTemplate("_internal/shortcodes/scn1.html", `<div>Outer, inner is {{ .Inner }}</div>`)
tem.AddTemplate("_internal/shortcodes/scn2.html", `<div>SC2</div>`)
return nil
@@ -262,7 +262,7 @@ func TestNestedSC(t *testing.T) {
func TestNestedComplexSC(t *testing.T) {
t.Parallel()
wt := func(tem tpl.TemplateHandler) error {
wt := func(tem tpl.TemplateManager) error {
tem.AddTemplate("_internal/shortcodes/row.html", `-row-{{ .Inner}}-rowStop-`)
tem.AddTemplate("_internal/shortcodes/column.html", `-col-{{.Inner }}-colStop-`)
tem.AddTemplate("_internal/shortcodes/aside.html", `-aside-{{ .Inner }}-asideStop-`)
@@ -278,7 +278,7 @@ func TestNestedComplexSC(t *testing.T) {
func TestParentShortcode(t *testing.T) {
t.Parallel()
wt := func(tem tpl.TemplateHandler) error {
wt := func(tem tpl.TemplateManager) error {
tem.AddTemplate("_internal/shortcodes/r1.html", `1: {{ .Get "pr1" }} {{ .Inner }}`)
tem.AddTemplate("_internal/shortcodes/r2.html", `2: {{ .Parent.Get "pr1" }}{{ .Get "pr2" }} {{ .Inner }}`)
tem.AddTemplate("_internal/shortcodes/r3.html", `3: {{ .Parent.Parent.Get "pr1" }}{{ .Parent.Get "pr2" }}{{ .Get "pr3" }} {{ .Inner }}`)
@@ -333,7 +333,7 @@ func TestFigureLinkWithTargetAndRel(t *testing.T) {
// #1642
func TestShortcodeWrappedInPIssue(t *testing.T) {
t.Parallel()
wt := func(tem tpl.TemplateHandler) error {
wt := func(tem tpl.TemplateManager) error {
tem.AddTemplate("_internal/shortcodes/bug.html", `xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`)
return nil
}
@@ -564,7 +564,7 @@ title: "Foo"
sources[i] = [2]string{filepath.FromSlash(test.contentPath), test.content}
}
addTemplates := func(templ tpl.TemplateHandler) error {
addTemplates := func(templ tpl.TemplateManager) error {
templ.AddTemplate("_default/single.html", "{{.Content}} Word Count: {{ .WordCount }}")
templ.AddTemplate("_internal/shortcodes/b.html", `b`)

View File

@@ -474,7 +474,7 @@ func NewSite(cfg deps.DepsCfg) (*Site, error) {
// The site will have a template system loaded and ready to use.
// Note: This is mainly used in single site tests.
// TODO(bep) test refactor -- remove
func NewSiteDefaultLang(withTemplate ...func(templ tpl.TemplateHandler) error) (*Site, error) {
func NewSiteDefaultLang(withTemplate ...func(templ tpl.TemplateManager) error) (*Site, error) {
v := viper.New()
if err := loadDefaultSettingsFor(v); err != nil {
return nil, err
@@ -486,7 +486,7 @@ func NewSiteDefaultLang(withTemplate ...func(templ tpl.TemplateHandler) error) (
// The site will have a template system loaded and ready to use.
// Note: This is mainly used in single site tests.
// TODO(bep) test refactor -- remove
func NewEnglishSite(withTemplate ...func(templ tpl.TemplateHandler) error) (*Site, error) {
func NewEnglishSite(withTemplate ...func(templ tpl.TemplateManager) error) (*Site, error) {
v := viper.New()
if err := loadDefaultSettingsFor(v); err != nil {
return nil, err
@@ -495,8 +495,8 @@ func NewEnglishSite(withTemplate ...func(templ tpl.TemplateHandler) error) (*Sit
}
// newSiteForLang creates a new site in the given language.
func newSiteForLang(lang *langs.Language, withTemplate ...func(templ tpl.TemplateHandler) error) (*Site, error) {
withTemplates := func(templ tpl.TemplateHandler) error {
func newSiteForLang(lang *langs.Language, withTemplate ...func(templ tpl.TemplateManager) error) (*Site, error) {
withTemplates := func(templ tpl.TemplateManager) error {
for _, wt := range withTemplate {
if err := wt(templ); err != nil {
return err
@@ -1589,7 +1589,7 @@ func (s *Site) renderForLayouts(name, outputFormat string, d interface{}, w io.W
return nil
}
if err = templ.Execute(w, d); err != nil {
if err = s.Tmpl.Execute(templ, w, d); err != nil {
return _errors.Wrapf(err, "render of %q failed", name)
}
return

View File

@@ -50,7 +50,7 @@ func doTestSitemapOutput(t *testing.T, internal bool) {
depsCfg := deps.DepsCfg{Fs: fs, Cfg: cfg}
depsCfg.WithTemplate = func(templ tpl.TemplateHandler) error {
depsCfg.WithTemplate = func(templ tpl.TemplateManager) error {
if !internal {
templ.AddTemplate("sitemap.xml", sitemapTemplate)
}

View File

@@ -1,97 +0,0 @@
// Copyright 2017 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hugolib
import (
"fmt"
"path/filepath"
"testing"
"github.com/gohugoio/hugo/deps"
)
// TODO1
func TestAllTemplateEngines(t *testing.T) {
noOp := func(s string) string {
return s
}
for _, config := range []struct {
suffix string
templateFixer func(s string) string
}{
//{"amber", amberFixer},
{"html", noOp},
//{"ace", noOp},
} {
config := config
t.Run(config.suffix,
func(t *testing.T) {
t.Parallel()
doTestTemplateEngine(t, config.suffix, config.templateFixer)
})
}
}
func doTestTemplateEngine(t *testing.T, suffix string, templateFixer func(s string) string) {
cfg, fs := newTestCfg()
t.Log("Testing", suffix)
templTemplate := `
p
|
| Page Title: {{ .Title }}
br
| Page Content: {{ .Content }}
br
| {{ title "hello world" }}
`
templShortcodeTemplate := `
p
|
| Shortcode: {{ .IsNamedParams }}
`
templ := templateFixer(templTemplate)
shortcodeTempl := templateFixer(templShortcodeTemplate)
writeSource(t, fs, filepath.Join("content", "p.md"), `
---
title: My Title
---
My Content
Shortcode: {{< myShort >}}
`)
writeSource(t, fs, filepath.Join("layouts", "_default", fmt.Sprintf("single.%s", suffix)), templ)
writeSource(t, fs, filepath.Join("layouts", "shortcodes", fmt.Sprintf("myShort.%s", suffix)), shortcodeTempl)
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{})
th := newTestHelper(s.Cfg, s.Fs, t)
th.assertFileContent(filepath.Join("public", "p", "index.html"),
"Page Title: My Title",
"My Content",
"Hello World",
"Shortcode: false",
)
}

View File

@@ -845,9 +845,9 @@ func newTestSitesFromConfig(t testing.TB, afs afero.Fs, tomlConfig string, layou
return th, h
}
func createWithTemplateFromNameValues(additionalTemplates ...string) func(templ tpl.TemplateHandler) error {
func createWithTemplateFromNameValues(additionalTemplates ...string) func(templ tpl.TemplateManager) error {
return func(templ tpl.TemplateHandler) error {
return func(templ tpl.TemplateManager) error {
for i := 0; i < len(additionalTemplates); i += 2 {
err := templ.AddTemplate(additionalTemplates[i], additionalTemplates[i+1])
if err != nil {