a-h / templ

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

question: How to pass JavaScript `arguments` to a script component? #494

Closed attila-kun closed 7 months ago

attila-kun commented 7 months ago

I have something like this:

<div
  hx-get={nextPageUrl}
  hx-on::response-error={handleError(id, arguments)}
>...</div>

script handleError(id string, args interface{}) {
    // do something with BOTH id and args
}

(arguments holds details regarding the error that has occurred.) This of course doesn't work because arguments is not a Go variable so I'm getting undefined: arguments. I can't use a simple <script></script> tag either because then I can't pass id which is a Go variable.

What do?

joerdav commented 7 months ago

Hi @attila-kun , could you help with the investigation of this by providing your templ version, and also the generated code that templ generate creates please?

attila-kun commented 7 months ago

Hi @joerdav, my templ version is: v0.2.543

Also, I simplified the example a bit, as it's actually not specific to HTMX attributes. Consider this:

templ buttonTempl(id int) {
    <button onclick={clickHandler(id, arguments[0])}>Click me!</button>
}

script clickHandler(id int, pointerEvent interface{}) {
    console.log(id, event);
}

The generated code is:

// Code generated by templ - DO NOT EDIT.

// templ: version: v0.2.543
package main

//lint:file-ignore SA4006 This context is only used if a nested component is present.

import "github.com/a-h/templ"
import "context"
import "io"
import "bytes"

func buttonTempl(id int) templ.Component {
    return templ.ComponentFunc(func(ctx context.Context, templ_7745c5c3_W io.Writer) (templ_7745c5c3_Err error) {
        templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templ_7745c5c3_W.(*bytes.Buffer)
        if !templ_7745c5c3_IsBuffer {
            templ_7745c5c3_Buffer = templ.GetBuffer()
            defer templ.ReleaseBuffer(templ_7745c5c3_Buffer)
        }
        ctx = templ.InitializeContext(ctx)
        templ_7745c5c3_Var1 := templ.GetChildren(ctx)
        if templ_7745c5c3_Var1 == nil {
            templ_7745c5c3_Var1 = templ.NopComponent
        }
        ctx = templ.ClearChildren(ctx)
        templ_7745c5c3_Err = templ.RenderScriptItems(ctx, templ_7745c5c3_Buffer, clickHandler(id, arguments[0]))
        if templ_7745c5c3_Err != nil {
            return templ_7745c5c3_Err
        }
        _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<button onclick=\"")
        if templ_7745c5c3_Err != nil {
            return templ_7745c5c3_Err
        }
        var templ_7745c5c3_Var2 templ.ComponentScript = clickHandler(id, arguments[0])
        _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var2.Call)
        if templ_7745c5c3_Err != nil {
            return templ_7745c5c3_Err
        }
        _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("\">Click me!</button>")
        if templ_7745c5c3_Err != nil {
            return templ_7745c5c3_Err
        }
        if !templ_7745c5c3_IsBuffer {
            _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteTo(templ_7745c5c3_W)
        }
        return templ_7745c5c3_Err
    })
}

func clickHandler(id int, pointerEvent interface{}) templ.ComponentScript {
    return templ.ComponentScript{
        Name: `__templ_clickHandler_0cd5`,
        Function: `function __templ_clickHandler_0cd5(id, pointerEvent){console.log(id, event);
}`,
        Call:       templ.SafeScript(`__templ_clickHandler_0cd5`, id, pointerEvent),
        CallInline: templ.SafeScriptInline(`__templ_clickHandler_0cd5`, id, pointerEvent),
    }
}

The error: ./button_templ.go:26:93: undefined: arguments

Which makes sense because arguments is indeed not a Go-accessible variable. It only exists at runtime, in the browser, not at render time. That being said, I'm not sure what a nice resolution to this problem is. One workaround is to do this:

templ buttonTempl(id int) {
    <button id={fmt.Sprintf("%d", id)} onclick="clickHandler(this, arguments[0])">Click me!</button>

    <script>
    function clickHandler(target, pointerEvent) {
        console.log(target.id, event);
    }
    </script>
}

But this is not ideal because it loses the benefits of the script block, e.g. being rendered only once.

joerdav commented 7 months ago

I would recommend the second solution you have provided. The syntax of onclick={clickHandler(id, arguments[0])} only works with Go parameters as you mentioned, and the values are resolved server side.

An alternative would be for you to grab one of the parameters in your script.

templ buttonTempl(id int) {
    <button onclick={clickHandler(id)}>Click me!</button>
}

script clickHandler(id int) {
    console.log(id, arguments[0]);
}

I'll close this for now, and if you have any other problems I'd direct you to either the templ Gopher slack channel, or the discussions section of this repo, as this isn't a bug or feature request.