tpl: Allow the partial template func to return any type

This commit adds support for return values in partials.

This means that you can now do this and similar:

    {{ $v := add . 42 }}
    {{ return $v }}

Partials without a `return` statement will be rendered as before.

This works for both `partial` and `partialCached`.

Fixes #5783
This commit is contained in:
Bjørn Erik Pedersen
2019-04-02 10:30:24 +02:00
committed by GitHub
parent 9225db636e
commit a55640de8e
11 changed files with 371 additions and 79 deletions

View File

@@ -180,7 +180,7 @@ PARAMS SITE GLOBAL3: {{ $site.Params.LOWER }}
func TestParamsKeysToLower(t *testing.T) {
t.Parallel()
_, err := applyTemplateTransformers(false, nil, nil)
_, err := applyTemplateTransformers(templateUndefined, nil, nil)
require.Error(t, err)
templ, err := template.New("foo").Funcs(testFuncs).Parse(paramsTempl)
@@ -484,7 +484,7 @@ func TestCollectInfo(t *testing.T) {
require.NoError(t, err)
c := newTemplateContext(createParseTreeLookup(templ))
c.isShortcode = true
c.typ = templateShortcode
c.applyTransformations(templ.Tree.Root)
assert.Equal(test.expected, c.Info)
@@ -492,3 +492,46 @@ func TestCollectInfo(t *testing.T) {
}
}
func TestPartialReturn(t *testing.T) {
tests := []struct {
name string
tplString string
expected bool
}{
{"Basic", `
{{ $a := "Hugo Rocks!" }}
{{ return $a }}
`, true},
{"Expression", `
{{ return add 32 }}
`, true},
}
echo := func(in interface{}) interface{} {
return in
}
funcs := template.FuncMap{
"return": echo,
"add": echo,
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
assert := require.New(t)
templ, err := template.New("foo").Funcs(funcs).Parse(test.tplString)
require.NoError(t, err)
_, err = applyTemplateTransformers(templatePartial, templ.Tree, createParseTreeLookup(templ))
// Just check that it doesn't fail in this test. We have functional tests
// in hugoblib.
assert.NoError(err)
})
}
}