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

Add to docs/ core the way to encode JSON via hsx #1900

Closed
amitaibu opened this issue Jan 29, 2024 · 4 comments · Fixed by #1934
Closed

Add to docs/ core the way to encode JSON via hsx #1900

amitaibu opened this issue Jan 29, 2024 · 4 comments · Fixed by #1934
Assignees

Comments

@amitaibu
Copy link
Collaborator

amitaibu commented Jan 29, 2024

import qualified Text.Blaze.Html.Renderer.Text as Renderer
import Text.Blaze.Html (Html)
import qualified Data.Text.Lazy as TL

instance ToJSON Html where
    toJSON html = String (TL.toStrict $ Renderer.renderHtml html)
    
    
<div data-my-encoded-json={encode someJsonValue}></div>
@amitaibu
Copy link
Collaborator Author

I've started an example. Surprisingly it seems I didn't need to declare the instance ToJSON Html where to make it work

amitaibu/ihp-cms-starter#37

@mpscholten
Copy link
Member

Likely because the encodereturns a Bytestring which cannot be directly rendered into the HTML. Can you try something like <div data-my-encoded-json={(cs (encode someJsonValue)) :: Text}></div>?

@mpscholten
Copy link
Member

With an instance ApplyAttribute Aeson.Value like:

-- IHP.HSX.Attribute
instance ApplyAttribute Aeson.Value where
    applyAttribute attr attr' value h = applyAttribute attr attr' value' h
        where value' = Html.textValue (encode someJsonValue)

we could also allow for this:

<div data-my-encoded-json={toJSON someJsonValue}></div>

This way we hide the technical implementation of the encode and the cs

@amitaibu
Copy link
Collaborator Author

The surprising part is that it's working as is:

<div data-my-encoded-json={encode someJsonValue}></div>

🤷

So I'll just go ahead and document it

amitaibu added a commit that referenced this issue Mar 16, 2024
mpscholten pushed a commit that referenced this issue Mar 18, 2024
* Docs about Passing JSON to the View

fixes #1900

* indent code

* Move toJSON code into the View
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants