Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doc: pass server-side data to the client #965

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions docs/docs/03-syntax-and-usage/12-script-templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,42 @@ The data in the script tag can then be accessed from client-side JavaScript.
const data = JSON.parse(document.getElementById('id').textContent);
```

Alternatively, you can add a helper that defines a constant, making it accessible in JavaScript scripts as a `const` variable.

```templ
// helper/helper.go
package helper

import (
"fmt"
"github.com/a-h/templ"
)

func AddScriptVar(k string, v string) templ.Component {
raw_script := fmt.Sprintf(`<script>const %s="%s"</script>`, k, v)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the key k or value v contains a quote ", the page could be subjected to a cross site-scripting attack.

return templ.Raw(raw_script)
}


// layout/base.templ
import "helper"

const HEADER = "xyztt"
templ Base() {
<html>
<head>...</head>
<body>
...
@helper.AddScriptVar("HX_header", HEADER)
<script>
console.log(HX_header) // xyztt
...
</script>
</body>
</html>
}
```

## Working with NPM projects

https://github.com/a-h/templ/tree/main/examples/typescript contains a TypeScript example that uses `esbuild` to transpile TypeScript into plain JavaScript, along with any required `npm` modules.
Expand Down