toJsonTemplate
Convert DOM elements into JSON templates for inspection or later rendering.
Convert DOM elements into JSON templates for inspection or later rendering.
Overview
The toJsonTemplate function is used to convert an HTML element or an array of HTML elements into a JSON structure. This can be useful for:
- Rendering HTML content in strict content security policy (CSP) pages.
- Improving rendering performance.
Try it live
<p>Hello, Regor</p>
raw produces the same string: true
SVG TAG<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8"/></svg>
{
"t": "p",
"c": [
{
"d": "Hello, Regor"
}
]
} ROUND TRIP Convert the JSON to a fragment, then back to JSON.
Generated strings are shown as text. Tagged templates assemble strings; they do not sanitize interpolated values.
import {
computed,
html,
raw,
ref,
svg,
toFragment,
toJsonTemplate,
} from 'regor'
export function createTemplates(interactive = false) {
const message = ref('Hello, Regor')
const json = computed(() => ({ t: 'p', c: [{ d: message() }] }))
const serialized = computed(() => JSON.stringify(json(), null, 2))
const tagged = computed(() => html`<p>${message()}</p>`)
const rawTagged = computed(() => raw`<p>${message()}</p>`)
const svgTagged = svg`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8"/></svg>`
const roundTrip = ref('Convert the JSON to a fragment, then back to JSON.')
const convert = () => {
const fragment = toFragment(json())
const element = fragment.firstElementChild!
roundTrip(JSON.stringify(toJsonTemplate(element), null, 2))
}
return {
interactive,
message,
serialized,
tagged,
rawTagged,
svgTagged,
roundTrip,
convert,
}
}
export const templatesTemplate = html` <div class="guide-demo">
<div class="guide-controls">
<label for="template-message">Text to encode</label
><input
id="template-message"
type="text"
maxlength="60"
r-model="message"
:value="message"
:disabled="!interactive"
/><button type="button" @click="convert" :disabled="!interactive">
JSON → fragment → JSON
</button>
</div>
<div class="directive-zones">
<article class="directive-card">
<span class="guide-kicker">HTML / RAW TAGS</span>
<pre class="api-snapshot" r-text="tagged"></pre>
<p>raw produces the same string: {{ tagged === rawTagged }}</p>
<span class="guide-kicker">SVG TAG</span>
<pre class="api-snapshot" r-text="svgTagged"></pre>
</article>
<article class="directive-card">
<span class="guide-kicker">JSON TEMPLATE</span>
<pre class="api-snapshot" r-text="serialized"></pre>
<span class="guide-kicker">ROUND TRIP</span>
<pre class="api-snapshot" r-text="roundTrip"></pre>
</article>
</div>
<p class="guide-hint">
Generated strings are shown as text. Tagged templates assemble strings; they
do not sanitize interpolated values.
</p>
</div>` import { createApp, RegorConfig, useScope } from 'regor'
import { apiExamples } from './examples'
const element = document.getElementById('api-demo')
const name = element?.dataset.example
if (element && name && Object.hasOwn(apiExamples, name)) {
const example = apiExamples[name as keyof typeof apiExamples]
const scope = useScope<object>(() => example.create(true))
const config =
'config' in scope.context && scope.context.config instanceof RegorConfig
? scope.context.config
: undefined
createApp(scope, { element, template: example.template }, config)
} Edit the text, then convert a JSON template into a detached fragment and serialize its element back to JSON.
Usage
Converting an HTML Element to JSON
To convert an HTML element to a JSON structure, call the toJsonTemplate function with the HTML element as the parameter. The function will return a JSON object that represents the structure of the HTML element.
Converting an Array of HTML Elements to JSON
You can also use the toJsonTemplate function to convert an array of HTML elements into an array of JSON structures. This is useful when you have multiple HTML elements that you want to convert to JSON.
Example
import { toJsonTemplate } from 'regor'
// Convert an HTML element to JSON
const element = document.querySelector('#myElement')
const jsonTemplate = toJsonTemplate(element)
// Convert an array of HTML elements to JSON
const elements = document.querySelectorAll('.myElements')
const jsonTemplates = toJsonTemplate(Array.from(elements)) Parameters
node: The HTML element or an array of HTML elements to be converted to JSON. It can be a singleElementor an array ofElementobjects.
Return Value
The toJsonTemplate function returns a JSON structure that represents the HTML element(s) passed as the parameter. The structure contains the following properties:
-
t(string): The tag name of the HTML element. This property is present if the HTML element has a tag name (e.g., "div", "p"). -
a(object): An object representing the attributes of the HTML element. Each attribute is a key-value pair in the object. -
c(array): An array of JSON structures representing the child elements of the HTML element. Each child element is converted to a JSON structure and added to this array. -
d(string): The content of a text node. Element text is represented by text-node entries insidec. -
n(number): The node type of the HTML element, specifically for comment nodes. This property is present if the HTML element is a comment node.
The JSON describes nodes and attributes. Event listeners and app state need their own context and binding step.
Notes
-
The
toJsonTemplatefunction can handle both single HTML elements and arrays of HTML elements. When converting an array, it returns an array of JSON structures. -
The resulting JSON structure can be used to render HTML content in strict content security policy (CSP) pages or to improve rendering performance.
-
This function is useful when you need to serialize HTML content to JSON or when you want to analyze the structure of HTML elements programmatically.
-
The JSON structure closely follows the structure of the HTML elements, including attributes, child elements, and text content.