Skip to content

How to pass data to html such as alpinejs? #519

Answered by a-h
sawirricardo asked this question in Q&A
Discussion options

You must be logged in to vote

components.templ

package main

templ Page(data any) {
	<div x-data={ toJSON(data) }>
		Content
	</div>
}

main.go

package main

import (
	"context"
	"encoding/json"
	"os"
)

func toJSON(v any) string {
	b, _ := json.Marshal(v)
	return string(b)
}

func main() {
	data := map[string]any{
		"i_want_to_put_here": "<data>",
	}
	Page(data).Render(context.Background(), os.Stdout)
}

go run .

The content is attribute escaped, but is valid JSON.

<div x-data="{&#34;i_want_to_put_here&#34;:&#34;\u003cdata\u003e&#34;}">Content</div>

Passing JavaScript objects on the client side.

I'm not familiar with alpine.js, but what you want seems similar to https://htmx.org/attributes/hx-vals/ in HTMX which can co…

Replies: 4 comments 4 replies

Comment options

You must be logged in to vote
3 replies
@sawirricardo
Comment options

@sawirricardo
Comment options

@a-h
Comment options

Answer selected by sawirricardo
Comment options

You must be logged in to vote
1 reply
@a-h
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants