-
Scenario:
Generated Go output unfortunately roughly: if obj.MyGlobalVarValue() != "" {
_, err = templBuffer.WriteString("<script>")
if err != nil {
return err
}
var_4 := `
previouslyDeclaredJSGlobal = '{ obj.MyGlobalVarValue() }' // <---oh-noez!
`
_, err = templBuffer.WriteString(var_4)
if err != nil {
return err
}
_, err = templBuffer.WriteString("</script>")
if err != nil {
return err
}
} Using Evidently |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi, and sorry for the late reply.
This is for safety. The script handling templates that templ does provide allow for the creation of JavaScript functions that accept parameters. These functions use JSON escaping for Go inputs to those functions to prevent malicious user-controlled strings from being used in unsafe contexts as per Google's SafeHTML. It could be possible to update templ to do context-aware escaping within script elements in future, but it's not supported today. However, templ is flexible, you can do whatever you want in Go code, even if it's unsafe. So, for this use case, if you're sure you want to do it, you can drop into a bit of Go. func RenderGlobalVariable(updated string) templ.Component {
return templ.ComponentFunc(func(ctx context.Context, w io.Writer) error {
// This is unsafe - there's no escaping of the updated value here.
s := fmt.Sprintf("<script>previouslyDeclaredJSGlobal = '%s';</script>", updated)
_, err := w.Write([]byte(s))
return err
})
} And you can use that inside your component, passing arbitrary Go strings.
There's a conversation going on around being able to call templ script templates from places other than element event handlers, that will provide an alternative solution to this when it ships. // Create a constant client-side variable.
templ page() {
<script>let globalVariable = "";</script>
}
// This creates a script tag with an "updateGlobal" JavaScript function inside it.
script updateGlobal(value string) {
globalVariable = value;
}
// This will render a script tag that calls the "updateGlobal" JavaScript function.
templ updateGlobalOnRender(withValue string) {
templ.Call(updateGlobal(withValue))
} |
Beta Was this translation helpful? Give feedback.
Hi, and sorry for the late reply.
<script>
tags are not currently interpreted by templ, i.e. there's currently no way to place Go strings directly inside script tags within templ.This is for safety. The script handling templates that templ does provide allow for the creation of JavaScript functions that accept parameters. These functions use JSON escaping for Go inputs to those functions to prevent malicious user-controlled strings from being used in unsafe contexts as per Google's SafeHTML.
It could be possible to update templ to do context-aware escaping within script elements in future, but it's not supported today.
However, templ is flexible, you can do whatever you want in Go code, …