Handling on events #228
Replies: 2 comments 2 replies
-
The current strategy would be to use standard JavaScript instead of script templates. You can use the "constant" version of HTML attributes to write any JavaScript you want. <input id="btn" type="button" onclick="(e) => alert(e)" value="Click" /> Or you can use a <script>
document.getElementById("btn").addEventListener("click", greet);
</script> However, I think that a small extension to the script template processing could satisfy the use case for script templates. We'd add a new Then, a convenience variable of // JSVar is a JavaScript variable. templ will not escape this value.
// The value must be a valid JavaScript identifier that is available at
// runtime.
type JSVar struct {
Name string
}
// Event is a JavaScript event variable, commonly used in event handlers.
var Event JSVar = JSVar{Name: "event"}
// SafeScript encodes unknown parameters for safety.
func SafeScript(functionName string, params ...any) string {
encodedParams := make([]string, len(params))
for i := 0; i < len(encodedParams); i++ {
if v, isJSVar := params[i].(JSVar); isJSVar {
encodedParams[i] = v.Name
continue
}
enc, _ := json.Marshal(params[i])
encodedParams[i] = EscapeString(string(enc))
}
sb := new(strings.Builder)
sb.WriteString(functionName)
sb.WriteRune('(')
sb.WriteString(strings.Join(encodedParams, ","))
sb.WriteRune(')')
return sb.String()
} In the template, you could then do this: script alert(e templ.JSVar) {
alert("Event: " + e);
alert("Target: " + e.target);
}
templ button(global, user int) {
<input type="button" value="Do something" onclick={ alert(templ.Event) }/>
} The output is rendered as: <script type="text/javascript">
function __templ_alert_3592(e){
alert("Event: " + e);
alert("Target: " + e.target);
}
</script>
<input type="button" value="Do something" onclick="__templ_alert_3592(event)"></div> I'd love to hear your thoughts on that. |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
-
How do you pass the event to the script functions when doing
onClick{Something()}
?Beta Was this translation helpful? Give feedback.
All reactions