developit / htm

Hyperscript Tagged Markup: JSX alternative using standard tagged templates, with compiler support.
Apache License 2.0
8.64k stars 169 forks source link

How to correctly handle these double quotes? #258

Closed jake-danton closed 4 months ago

jake-danton commented 4 months ago

I am trying to figure out how to get this valid html working with htm:

html`
      <html>
        <head>
            <script type="importmap">
                {
                    "imports": {
                        "preact-iso": "https://esm.sh/preact-iso@2.4.0"
                    }
                }
            </script>
...

As is, it renders as:

<html><head><script type="importmap">{&quot;preact-iso&quot;:&quot;https://esm.sh/preact-iso@2.4.0&quot;}}</script>
...

Which is invalid HTML. And single quotes won't work here as it keeps them single quotes in the output and the result is invalid JSON.

Is there a way to correctly handle this? Something like unsafeHtml in lit that would let me concatenate the JSON object as a string directly parsed as a VNode?

rschristian commented 4 months ago

dangerouslySetInnerHTML is what you want:

const MAP = {
    imports: {
        "preact-iso": "https://esm.sh/preact-iso@2.4.0"
    }
};

const doc = html`
    <html>
        <head>
            <script type="importmap" dangerouslySetInnerHTML=${{ __html: JSON.stringify(MAP) }}></script>
        </head>
    </html>
`;
jake-danton commented 4 months ago

Thank you @rschristian !