Closed bshore closed 9 months ago
Repo: https://github.com/bshore/htmx-contact-app
File where I noticed the behavior: https://github.com/bshore/htmx-contact-app/blob/7140c9d5332c03a361ebac6503dc9d633a1af353/internal/views/edit.templ
@bshore These are the only attributes at the moment which require sanitizing URLs, however you can still leverage the sensitization function, with some slightly verbose code, in your case it would be:
<input
name="email"
id="email"
type="email"
hx-get={ string(templ.URL(fmt.Sprintf("/contacts/%s/email", contact.ID))) }
...
/>
An option to reduce this would be for a new function templ.SanitizeURL(string) string
, which encapsulates the functionality of templ.URL(string) templ.SafeURL
, but returns a string. But as you can see it doesn't involve any less typing:
string(templ.URL(fmt.Sprintf("/contacts/%s/email", contact.ID)))
templ.SanitizeURL(fmt.Sprintf("/contacts/%s/email", contact.ID))
@joerdav So maybe instead what I can do is contribute a docs update for others that may encounter this.
A note here about non-standard HTML attributes that contain URLs ( i.e. HTMX )
https://templ.guide/syntax-and-usage/attributes/#url-attributes
I agree, a small note on the fact that this function can be used independent of href
/action
would be useful I think.
I'm working through the HTMX book and I noticed the
templ
generator only generates sanitized URLs for:<a href=""></a>
<form action=""></form>
Generator code reference
I believe this is where the issue is - https://github.com/a-h/templ/blob/v0.2.513/generator/generator.go#L1084
Working as expected
On a
<form action=""></form>
or<a href=""></a>
the generator defines theSafeURL
on a separate line, and then casts it withstring()
when writing.Generates
Generator produces error
On anything other than an
<a href=""></a>
or<form action=""></form>
is written as a single line and causes an error.Generates
Workaround
I do have a workaround and it's totally fine, I just skip doing
templ.URL
onhx-*
attributes:Contribute
I'd like to contribute a fix for this if possible, maybe checking for these attributes?
hx-get
hx-post
hx-put
hx-patch
hx-delete
Or maybe is there a way to make an allow list? Any ideas?