Hi Ian / Dan,
I really appreciate there are workarounds, I use golang templates a lot so I know - in many places I have to write functions that are workarounds.
I have a template function "html" that simply returns template.html of a string.
Because the options are set by user settings and it's all buried deep in iterative loops of producing reports this is what I finally did:
The original h2 and h3 lines look something like this where there are many uses of h2, h3
<h2 id="{{$id}}"><b>{{$.sectionNumber}}.{{$.section}} {{.ProcessLibrary.FullName}}</b></h2>
So because this can now be part of a small or large generated document, now h2 can be h3 or even h4 etc.
So I create the variable h2 further up in the code with something like this - it isn't this but you get the idea
{{- $h2 := html (printf 'h%d' .level)}}
and the line I would have preferred would be very readable (not to mention a quick search and replace)
<{{$h2}} id="{{$id}}"><b>{{$.sectionNumber}}.{{$.section}} {{.ProcessLibrary.FullName}}</b></{{$h2}}>
Perfectly valid HTML in the end
The workaround I implemented is as follows:
Change creation of $h2 to a plain old string
{{- $h2 := printf 'h%d' .level}}
Do this in every place where it was <h2> .. </h2>
{{html (printf `<%s id="%s">` $h2 $id) -}}
{{$.sectionNumber}}.{{$.section}} {{.FullName}}
{{- html (printf `</%s>` $h2)}}
I agree I could have created $h2o and $h2c for opening and closing formats near the top but as I have the ID for table of contents I anyway need to create the tagged value dynamcally.
I could have even written javascript to fix it. There are many workarounds, all of which become harder for someone to understand when they look at the code in 2 years time.
However if there are many workarounds, why is GO being so sanctimonious? Maybe that's good for day 1 newbie but not seasoned developer!! Sure I could use some 3rd party library with different template logic. But what's wrong with a template.unsafe function that just accepts I know what I'm doing and doesn't try and police things and anyway has workarounds.
I really wrote this because I come across issues like this a lot with GO templates and wondered if I just was missing some obvious faux pas. It seems not - I just have to keep writing the workarounds for GO not allowing tags to be changed dynamically. Unexpected escaping is quite frustrating in GO templates.
Regards,
Tim.