a-h / templ

A language for writing HTML user interfaces in Go.
https://templ.guide/
MIT License
7.14k stars 236 forks source link

Proposal: Change URL's signature to match [S]Printf #798

Open emehrkay opened 2 weeks ago

emehrkay commented 2 weeks ago

Go from:

func URL(s string) SafeURL {

To:

func URL(format string, a ...any) SafeURL {
   s := fmt.Sprintf(format, a...)

This would be a backwards compatible change and would save some function nesting in templ funcs

joerdav commented 1 week ago

I think it would be standard form for that to be an extra function that ends with f such as URLf. I believe that this standard is used by editors to highlight the format string differently.

a-h commented 1 week ago

I like the idea of having a url format / builder function.

If it was the signature of Sprintf, e.g.: urlf.Sprintf("/path/%s/fileName.js?%s=%v", "pathvar/", "qkey?", "&other=true") there's a few dangers to consider... Because of the context of the variable substitution, there's a risk of injection attacks, so the values would need to be appropriately escaped:

There's also the question of what happens if you do something like:

urlf.Sprintf("?%s", "data")

It could live in github.com/a-h/templ/urlf to avoid the name of oddity of templ.URLf or similar, but I don't mind templ.URL

I wonder if a builder style is better, since it turns issues with sprintf replacement into compile time issues:

urlbuilder.Build().Path("a").Path("b").Path(c).Query(key, value)
joerdav commented 1 week ago

There could be an unsafe counterpart too, urlf.UnsafeSprintf.