html / template:子模板周围的可选外部元素(如果不为空)

I have a template with an inner content template and I want to render it in a way that there is an outer wrapping element around inner content which is only shown if the content is not empty.

For example:

...
{{if template-content-exists-and-not-blank}}
  <div class="content">
   {{template "content" .}}
  </div>
{{end}}
...

I want to render <div> only when the result of {{template "content" .}} is not empty. I don't want to put the enclosing <div> into content, as it doesn't really belong there, and it will be duplicated across all content sub-templates.

  1. I cannot use {{template ...}} as a function argument, so it's not possible to test it.
  2. I wrote a custom defined boolean function that tests if a sub-template is defined, but the content template is executed regardless of whether it's true or false (no short-circuiting), and obviously fails if it's not defined.

    t.Funcs(
        html.FuncMap{
            "defined": func(name string) bool {
                return t.Lookup(name) != nil
            },
        },
    )
    

You would need to do one of two things:

  1. Put the containing tag in the sub-template
  2. Pre-render the sub-template and pass it to the outer template as a string