Dynamic tag name results in string HTML node

<{{ $titletag | safeHTML }}>foo</{{ $titletag | safeHTML }}>

results in


which looks correct, however, <p>foo</p> is a string HTML node, not an element.

Is there a way to get this to work like I want?

{{ printf "<%s>" $t | safeHTML }}foo{{ printf "</%s>" $t | safeHTML }}

Thanks for the suggestion. Unfortunately, the tag has attributes, so putting it in a string would be a pain, e.g.:

<{{ $titletag }} {{ with $titleclass }} class="{{ . }}" {{ end }}>{{ with $titlelink }}<a href="{{ . }}">{{ $title }}</a>{{ else }}{{ $title }}{{ end }}{{ with $titlepage }}<a aria-label="Link to this section" class="paige-header-link" href="{{ . }}">#</a>{{ end }}</{{ $titletag }}>

Duplicating the line in an if/else and hard-coding the tag name does work, but it’s not DRY.

If can you can put your attributes in a map, you can iterate to build the element.

For an anchor element…

{{- range $k, $v := $attrs }}
  {{- printf " %s=%q" $k $v | safeHTMLAttr }}
{{- end -}}
>{{ .Text | safe.HTML }}</a>
1 Like