go - How can I override a template block with an empty template? -
using text/html
define block
in base template, containing default content. in situations block empty, thought re-define name , make contain nothing like:
{{ block "something" . }} <h1>default content</h1> {{ end }} // later in place not want "something" ... {{ define "something" }}{{ end }}
somehow go seems think definition "zero" , still render default content unless put non-whitespace content definition.
i found this issue on golang repo describes same thing nicely in a playground example:
package main import ( "fmt" "os" "runtime" "text/template" ) func main() { fmt.printf("version: %q\n", runtime.version()) t, err := template.new("master").parse(`{{block "area51" .}}original content{{end}}`) if err != nil { panic(err) } t, err = t.new("other_template").parse(`{{define "area51"}}{{end}}`) if err != nil { panic(err) } fmt.printf("output:\n") if err := t.executetemplate(os.stdout, "master", nil); err != nil { panic(err) } fmt.printf("\n") }
weirdly, issue mention fixed (and landed in 1.8.1 if understand correctly), not work me, neither 1.8.1+ nor 1.9.
is bug in golang or approach flawed? need differently in order re-define block renders empty?
this expected behavior. documented @ template.parse()
:
templates can redefined in successive calls parse, before first use of execute on t or associated template. a template definition body containing white space , comments considered empty , not replace existing template's body. allows using parse add new named template definitions without overwriting main template body.
so can't "erase" defined template (you can't replace content empty).
if "conditionally" need it, use {{if}}
action decide if template called. alternatively may put {{if}}
inside template, , template may choose not render anything. in case have make sure pass proper argument controls template render.
p.s. if you're working html templates, should use html/template
instead of text/template
, former provides same interface package text/template
provides contextual escaping generate html output safe against code injection.
Comments
Post a Comment