toFragment
Build a DocumentFragment from a JSON template describing HTML or SVG.
Build a DocumentFragment from a JSON template describing HTML or SVG.
Overview
The toFragment function is used to convert a JSON template, representing HTML or SVG elements, into a DocumentFragment. This can be particularly useful when you want to create a lightweight, in-memory representation of the DOM structure for further manipulation or rendering.
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 a JSON Template to a DocumentFragment
To convert a JSON template to a DocumentFragment, call the toFragment function with the JSON template as the parameter. The function will return a DocumentFragment containing the converted elements.
Example
import { toFragment } from 'regor'
// Define a JSON template representing HTML elements
const jsonTemplate = {
t: 'div',
a: { class: 'container' },
c: [
{
t: 'h1',
a: { class: 'title' },
c: [{ d: 'Hello, Regor!' }],
},
{
t: 'p',
c: [{ d: 'Regor is awesome.' }],
},
],
}
// Convert the JSON template to a DocumentFragment
const fragment = toFragment(jsonTemplate)
// Append the DocumentFragment to the DOM
const targetElement = document.getElementById('app')
targetElement.appendChild(fragment) Parameters
-
json: The JSON template to be converted into a DocumentFragment. It can represent one or more HTML or SVG elements. If an array of JSON templates is provided, each template will be converted, and their resulting elements will be added to the DocumentFragment. -
isSVG(optional): A boolean flag indicating whether the elements in the JSON template should be treated as SVG elements. If set totrue, SVG-specific elements and attributes will be correctly created. Default isfalse. -
config(optional): An instance ofRegorConfigthat defines configuration options for Regor. This can be used to specify custom attribute handling and other options. If not provided, the defaultRegorConfigwill be used.
Return Value
The toFragment function returns a DocumentFragment containing the elements created from the provided JSON template(s).
toFragment builds DOM structure. Use createApp when those nodes should also participate in Regor bindings.
Notes
-
The
toFragmentfunction is useful for creating DocumentFragments that can be used for lightweight rendering and manipulation of DOM structures. -
It can handle both HTML and SVG elements in the JSON template, depending on the
isSVGflag. -
The resulting
DocumentFragmentcan be appended to the DOM or further manipulated using standard DOM methods. -
Use
tfor an element,afor its attributes, andcfor its child nodes. A text node usesd; element text belongs in a child such asc: [{ d: 'Hello' }]. -
Custom attribute handling and other options can be configured using the
configparameter.