Home > Software engineering >  How to add an HTML Tag Attribute in GoLang Template
How to add an HTML Tag Attribute in GoLang Template

Time:01-22

I have the following code:

{{range . }}
    <td {{ if not .IsDisabled }}onclick="return toggle_active($(this))"{{ end }}>
      [x]
    </td>
{{end}}

This works, it puts the onclick event like it should.

However, if I try to create the onclick event dynamically as a string (either in the template, or as a Go function, it doesn't work.

Example:

{{$clickEvent := "return toggle_active($(this));"}}
<td {{$clickEvent}}>[x]</td>

Or:

func (d TemplateObject) Click() string {
    return "onclick=\"toggle_active($(this))\""
}

<td {{.Click}}>[x]</td>

It renders it like this in the HTML:

enter image description here

If I don't put it in the <tag> itself <td>{{$ClickEvent}}</td> it prints it as a string.

How can I get the attribute to render correctly?

CodePudding user response:

You need to do

func (d TemplateObject) Click() template.HTMLAttr {
    return "onclick=\"toggle_active($(this))\""
}

so that it knows the string is safe to use as an attribute

https://pkg.go.dev/html/template#HTMLAttr

HTMLAttr encapsulates an HTML attribute from a trusted source, for example, dir="ltr". Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.

  • Related