1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, so simple. That was it. Appreciate the quick response

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.