### Install Fragtml Package
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Installs the Fragtml library using npm. This is a prerequisite for using Fragtml in your project.
```sh
npm install fragtml
```
--------------------------------
### Start a Named Fragment Range
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Illustrates the usage of `html.fragment.start(id)` to mark the beginning of a named fragment within a template.
```javascript
${html.fragment.start('archive-ui')}
```
--------------------------------
### Using Fragment Boundaries in a Template
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Demonstrates how to use start and end fragment boundary objects within an HTML template literal to define a fragment.
```javascript
html`
${html.fragment.start('archive-ui')}
${html.fragment.end}
`
```
--------------------------------
### Boolean Attributes - Falsey Example
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Example showing the output when the condition for a boolean attribute is falsey.
```html
```
--------------------------------
### Render Archive Button Fragment with FragTML
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
This example demonstrates rendering only a specific fragment, the archive button, by providing a `fragmentId` to the `contactDetail` function. This allows for partial updates or targeted rendering.
```javascript
contactDetail({ contact, fragmentId: 'archive-ui' })
```
--------------------------------
### Editor Highlighting with '/* html */' Marker
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
This example shows how to ensure editor HTML highlighting works correctly when using fragment aliases by adding an `/* html */` marker. It uses the `frag` alias and defines a template with an archive button.
```javascript
const h = frag(fragmentId)
return h/* html */`
`
```
--------------------------------
### Named and Unnamed Fragment Boundary Objects
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Illustrates the structure of start and end boundary objects used for fragment support. The start boundary includes an ID, while the end boundary is unnamed.
```javascript
{
[fragmentBoundarySymbol]: true,
kind: 'start',
id: 'archive-ui'
}
```
```javascript
{
[fragmentBoundarySymbol]: true,
kind: 'end'
}
```
--------------------------------
### Boolean Attributes - Truthy Example
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Example showing the output when the condition for a boolean attribute is truthy.
```html
```
--------------------------------
### Nested Template Composition Example
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Shows how a nested template result is treated as a recognizable library-created value, allowing parent templates to insert it without escaping its markup.
```javascript
const child = html`${''}`
const parent = html`
${child}
`
render(parent)
// '
<Bret>
'
```
--------------------------------
### End a Fragment Range
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Demonstrates the usage of `html.fragment.end` to close the most recently opened fragment range started with `html.fragment.start()`.
```javascript
${html.fragment.end}
```
--------------------------------
### Example of Stale Cache Behavior
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Demonstrates how caching final rendered strings can lead to stale output when substitutions are mutated. `HtmlResult` should render from its captured template and substitutions each time it is called.
```javascript
const items = ['a']
const result = html`${items}`
items.push('b')
render(result)
// should reflect the current substitution semantics, not a stale first-render cache
```
--------------------------------
### Fragment Markers with FragmentTemplateTypes
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
This example demonstrates using `FragmentTemplateTypes` to define context types for different fragments within a single template. It shows how to define fragment IDs, their required context types, and the overall context for the full template. The `PageArgs` type enforces context requirements at the call boundary.
```typescript
import { frag, render } from 'fragtml'
import type {
FragmentTemplateTypes
} from 'fragtml/types.js'
type InnerPageContext = {
text: string
}
type OuterPageContext = InnerPageContext & {
title: string
}
type FullPageContext = OuterPageContext & {
foo: string
}
type PageTemplate = FragmentTemplateTypes<{
// Fragment IDs and their required context types.
fragments: {
inner: InnerPageContext
outer: OuterPageContext
}
// Context required to render the full template.
full: FullPageContext
}>
type PageFragment = PageTemplate['fragmentId']
// Resolves to:
// 'inner' | 'outer'
type PageArgs = PageTemplate['args']
// Resolves to:
// | { fragmentId: 'inner', context: InnerPageContext & Record }
// | { fragmentId: 'outer', context: OuterPageContext & Record }
// | { fragmentId?: undefined, context: FullPageContext & Record }
type PageTemplateArgs = PageTemplate['templateArgs']
// Resolves to:
// {
// fragmentId?: 'inner' | 'outer' | undefined
// context: {
// foo?: string
// title?: string
// text?: string
// }
// }
function pageTemplate ({
context,
fragmentId
}: PageTemplateArgs) {
const html = frag(fragmentId)
return html`
${context.foo}
${html.fragment.start('outer')}
${context.title}
${html.fragment.start('inner')}
${context.text}
${html.fragment.end}
${html.fragment.end}
`
}
export function page (args: PageArgs) {
return render(pageTemplate(args))
}
// These calls are still type-safe: PageArgs enforces the required context
// fields for each fragment target at the public call boundary.
page({
fragmentId: 'inner',
context: { text: 'Updated body text' }
})
page({
fragmentId: 'outer',
context: {
// Extra already-loaded data is allowed.
foo: 'Full page field',
title: 'Outer fragment title',
text: 'Updated body text'
}
})
page({
context: {
foo: 'Full page field',
title: 'Outer fragment title',
text: 'Updated body text'
}
})
// @ts-expect-error outer fragments require both title and text.
page({
fragmentId: 'outer',
context: { text: 'Missing the outer title' }
})
```
--------------------------------
### Dashboard Template with Fragments
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Defines a dashboard template using Fragtml fragments, allowing for partial updates to specific sections like account information or feed items while keeping the overall page structure intact. Includes type definitions for context and examples of rendering different fragments.
```typescript
import html, { render } from 'fragtml'
import type { FragmentTemplateTypes } from 'fragtml/types.js'
function dashboardTemplate ({
account,
feed,
fragmentId
}: DashboardTemplate['templateArgs']) {
return html(fragmentId)/* html */`
`)
}
```
--------------------------------
### Defining Fragments with Boundary Tokens
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Illustrates how to define named fragments within a template using `html.fragment.start` and `html.fragment.end` boundary tokens.
```javascript
${html.fragment.start('archive-ui')}
...
${html.fragment.end}
```
--------------------------------
### Basic fragtml Template Tag Usage
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Demonstrates the basic usage of the `html` template tag for creating HTML structures with dynamic values.
```javascript
html`
${value}
`
```
--------------------------------
### Callable HTML Tag with Properties
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Demonstrates how to use the html tag function at runtime, exposing helper properties for fragments and raw HTML.
```javascript
html.fragment = createFragmentHelpers()
html.raw = raw
const h = html({ fragmentId })
h.fragment = html.fragment
h.raw = raw
```
--------------------------------
### Basic HTML Rendering
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Demonstrates basic HTML string creation and rendering using the html tag and render function. Interpolated values are escaped by default.
```javascript
import html, { render } from 'fragtml'
const name = ''
const result = html`
Hello ${name}
`
render(result)
// '
Hello <Bret>
'
```
--------------------------------
### Publish a Release to npm
Source: https://github.com/bcomnes/fragtml/blob/master/CONTRIBUTING.md
After updating the version, use this command to push your local branch and tags, create a GitHub release, and publish the package to npm. This command also performs a gh-release.
```bash
npm publish
```
--------------------------------
### Create a Release with npm Version
Source: https://github.com/bcomnes/fragtml/blob/master/CONTRIBUTING.md
Use this command to update the version number and automatically generate a changelog for a new release. Ensure your git workspace is clean before running.
```bash
npm version {patch, minor, major}
```
--------------------------------
### html.fragment.start(id)
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Marks the beginning of a named fragment range within a template, allowing for targeted rendering of specific sections.
```APIDOC
## `html.fragment.start(id)`
Starts a named fragment range.
```js
${html.fragment.start('archive-ui')}
```
```
--------------------------------
### Import fragtml Type Guards
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Demonstrates importing and using public type guard functions provided by fragtml to check the type of values.
```javascript
import {
isFragmentBoundary,
isHtmlResult,
isRawHtml
} from 'fragtml'
```
--------------------------------
### Import fragtml TypeScript Types
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Demonstrates importing type-only aliases from `fragtml/types.js` for use in TypeScript projects.
```typescript
import type {
FragmentArgs,
FragmentIdOf,
FragmentTemplateArgs,
FragmentTemplateTypes,
HtmlRenderable,
HtmlResult,
HtmlTag,
RawHtml,
RenderOptions
} from 'fragtml/types.js'
```
--------------------------------
### Template Caching Implementation
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Shows a recommended implementation for caching static template processing using a `WeakMap`. This approach caches precomputed metadata for a given template literal call site.
```javascript
const templateCache = new WeakMap()
function compileTemplate (strings, mode) {
let compiled = templateCache.get(strings)
if (!compiled) {
compiled = {
strings,
mode,
// static preprocessing metadata here
}
templateCache.set(strings, compiled)
}
return compiled
}
```
--------------------------------
### Render Full Page with FragTML
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
This snippet shows how to render an entire HTML page using the `contactDetailTemplate` function and the `render` utility from FragTML. It includes dynamic content based on contact details and HTMX attributes for interactivity.
```javascript
import html, { render } from 'fragtml'
function contactDetailTemplate ({ contact, fragmentId }) {
return html(fragmentId)`
`
}
export function contactDetail (args) {
return render(contactDetailTemplate(args))
}
```
--------------------------------
### Safe Nested Composition with Fragml
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Demonstrates how to use `html` to create nested template objects that can be safely rendered. Interpolated strings are escaped by default.
```javascript
import html, { render } from 'fragtml'
const button = html``
const panel = html`
${button}
`
render(panel)
// ''
```
--------------------------------
### Render Root Fragment with fragtml
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Renders the entire 'profile' fragment, including its nested content. This is useful for updating a large section of the page.
```javascript
page({ fragmentId: 'profile' })
// '
//
Profile
//
//
// '
```
--------------------------------
### Using html.raw Helper
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Shows that `html.raw` is an alias for the `raw` helper, allowing trusted HTML insertion directly from the `html` tag object.
```javascript
html.raw === raw
// true
```
--------------------------------
### Import fragtml Error Classes
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Shows how to import specific error classes from fragtml for error handling and type checking.
```javascript
import {
DuplicateFragmentError,
FragmentBoundaryError,
FragmentNotFoundError
} from 'fragtml'
```
--------------------------------
### Raw HTML Helper Usage
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Shows how to use the `raw` helper function or the `.raw()` method on an `html` tag instance to insert trusted, unescaped HTML content.
```typescript
html.raw('trusted')
raw('trusted')
```
--------------------------------
### Rendering XML/RSS Feed
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Demonstrates rendering XML-shaped documents, such as RSS feeds, with FragTML. Static markup is preserved, and interpolated values are escaped.
```javascript
import html, { render } from 'fragtml'
const siteUrl = 'https://example.com'
const posts = [
{
title: 'Hello & welcome',
href: '/posts/hello'
}
]
const feed = html`
Example Feed
${siteUrl}
${posts.map(post => html`
${post.title}
${siteUrl}${post.href}
${siteUrl}${post.href}
`)}
`
render(feed)
// '
...'
```
--------------------------------
### Returning Rendered HTML from Route Handlers
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Shows how to return rendered HTML from a route handler. The render function should be used at route-handler boundaries.
```javascript
return render(html`
${title}
`)
```
--------------------------------
### Using fragtml Alias for Editor Highlighting
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Illustrates using `frag` as an alias for `html` and assigning it to a local variable `h` for better editor highlighting, especially with the `/* html */` marker.
```javascript
import { frag } from 'fragtml'
const html = frag(fragmentId)
const h = frag(fragmentId)
return h/* html */`
${value}
`
```
--------------------------------
### Trusted Raw HTML Insertion
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Demonstrates how to insert pre-trusted HTML content into a template using the `raw` helper. The content provided to `raw` is not escaped.
```javascript
import html, { raw, render } from 'fragtml'
const result = html`
${raw('trusted')}
`
render(result)
// '
trusted
'
```
--------------------------------
### Creating Raw Trusted HTML
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Demonstrates the use of the `.raw` helper to create a separate branded raw/trusted value for HTML content that should not be escaped.
```javascript
html.raw('trusted')
```
--------------------------------
### Basic HTML Tag Usage
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Illustrates the basic usage of the `html` tag for creating safe HTML interpolations and rendering the result.
```typescript
import html, { createHtml, html as namedHtml, raw, render } from 'fragtml'
const result = html`
${'safe'}
`
render(result)
String(result)
```
--------------------------------
### Mark Trusted HTML with raw
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Shows how to use the `raw` function to mark HTML content as trusted, preventing it from being escaped during rendering.
```javascript
html`
${raw('trusted')}
`
```
--------------------------------
### Select Fragment with ID using html Tag
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Shows how to select and render a specific fragment from a template by passing its ID to the `html` tag.
```javascript
html('name')`...`
```
```javascript
html({ fragmentId: 'name' })`...`
```
--------------------------------
### Using a Bound Tag for Fragment Definition
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Demonstrates a common pattern where a bound tag `h` is created with a `fragmentId` for cleaner template syntax, especially when editors might not highlight call expressions as reliably.
```javascript
({ fragmentId, ...data }) => {
const h = html({ fragmentId })
return render(h`
...
`)
}
```
--------------------------------
### Shorter Render-Target Overload for Fragments
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Demonstrates the convenience overload `html('fragment-id')` which is equivalent to `html({ fragmentId: 'fragment-id' })` for defining fragments.
```javascript
html('archive-ui')`...`
```
--------------------------------
### Direct String Conversion of Template Results
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Demonstrates the various ways a template result object can be converted to a string, including String(), toString(), and template literal interpolation.
```javascript
const result = html`
${name}
`
String(result)
result.toString()
`${result}`
```
--------------------------------
### render(value)
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
The `render` function converts a `fragtml` tagged template result into a primitive string representation of the HTML.
```APIDOC
## `render(value)`
Converts a `fragtml` result to a primitive string.
```js
render(html`
${value}
`)
```
```
--------------------------------
### Render fragtml Result to String
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Demonstrates how to convert a `fragtml` `HtmlResult` object into a primitive string using the `render` function.
```javascript
render(html`
${value}
`)
```
--------------------------------
### Rendering Raw HTML Content within Fragments
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Explains how to render trusted HTML content directly within a fragment using the `h.raw()` helper, while other interpolations follow safe rules.
```javascript
const h = html({ fragmentId })
render(h`
${h.fragment.start('raw-widget')}
${h.raw(trustedHtml)}
${h.fragment.end}
`)
```
--------------------------------
### Basic Safe HTML Rendering
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Illustrates the default safe behavior of the `html` tag, where interpolated values are automatically HTML-escaped. Shows conversion to a primitive string using `String()` and the `render()` function.
```javascript
import html, { render } from 'fragtml'
const name = ''
const result = html`
Hello ${name}
`
String(result)
// '
Hello <Bret>
'
render(result)
// '
Hello <Bret>
'
```
--------------------------------
### Rendering Trusted Raw HTML
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Demonstrates using the `raw()` function or `html.raw` to render HTML content that should not be escaped. Only pass trusted HTML to `raw()`.
```javascript
import html, { raw, render } from 'fragtml'
render(html`
${raw('trusted')}
`)
// '
trusted
'
html.raw === raw
render(html`
${html.raw('trusted')}
`)
// '
trusted
'
```
--------------------------------
### Avoid Wrapping Entire Template in Outer Fragment
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Demonstrates an antipattern of wrapping the entire template in an outer fragment, which adds a fake target without changing output.
```javascript
function pageTemplate ({ fragmentId }) {
return html(fragmentId)`
${html.fragment.start('page')}
${title}
${body}
${html.fragment.end}
`
}
```
--------------------------------
### Composed Dashboard Template with Function Composition
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Builds a dashboard using function composition for reusable partial templates. This approach simplifies types and reduces moving parts compared to fragments, but spreads the full-page structure across multiple functions.
```typescript
function accountPrimaryAction (context: AccountActionContext) {
return html`
`
}
function accountRoot (context: AccountRootContext) {
return html`
${context.account.title}
${context.account.name}
${accountPrimaryAction(context)}
`
}
function feedItemMenu (context: FeedItemMenuContext) {
return html`
`
}
function feedRoot (context: FeedRootContext) {
return html`
${accountRoot(context)}
${feedRoot(context)}
`
}
export function composedDashboard (context: AccountRootContext & FeedRootContext) {
return render(composedDashboardTemplate(context))
}
```
--------------------------------
### Render Nested Fragment with fragtml
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Renders only the 'profile-actions' nested fragment. This is useful for updating small, specific parts of the UI independently.
```javascript
page({ fragmentId: 'profile-actions' })
// ''
```
--------------------------------
### Prefer Direct Template Rendering Without Outer Fragment
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Shows the preferred way to render a template directly, avoiding unnecessary outer fragments for full template rendering.
```javascript
function pageTemplate ({ fragmentId }) {
return html(fragmentId)`
${title}
${body}
`
}
```
--------------------------------
### Build Public Argument Union with FragmentArgs
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Constructs the public argument union type using FragmentArgs, combining fragment contexts and the full-page context.
```typescript
type PageArgs = FragmentArgs<{
inner: InnerPageContext
outer: OuterPageContext
}, FullPageContext>
// Equivalent to:
// | { fragmentId: 'inner', context: InnerPageContext & Record }
// | { fragmentId: 'outer', context: OuterPageContext & Record }
// | { fragmentId?: undefined, context: FullPageContext & Record }
```
--------------------------------
### Avoiding Shadowing with createHtml Alias
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Shows how to use `createHtml` when the local tag needs to be named `html` to prevent JavaScript name shadowing, ensuring the template tag is a simple identifier.
```javascript
import { createHtml, render } from 'fragtml'
export function view ({ fragmentId }) {
const html = createHtml({ fragmentId })
return render(html`
${html.fragment.start('main')}
...
${html.fragment.end}
`)
}
```
--------------------------------
### Define Nested Fragments with fragtml
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Defines a page template with nested fragments for profile and activity sections. This allows for independent rendering of parent and child regions.
```javascript
import html, { render } from 'fragtml'
function pageTemplate ({ fragmentId }) {
return html(fragmentId)`
${html.fragment.start('profile')}
'
```
--------------------------------
### Preferred Explicit Rendering Boundary
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Illustrates the preferred method for explicit rendering of template results, particularly for route handlers and tests, using the render() function.
```javascript
return render(html`
${name}
`)
```
--------------------------------
### Using 'frag' Alias for HTML Templating
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
This snippet illustrates using the `frag` alias for `html` to improve editor highlighting. It defines a template for contact details, including an archive button, within an `` tag.
```javascript
import { frag, render } from 'fragtml'
function contactDetailTemplate ({ contact, fragmentId }) {
const html = frag(fragmentId)
return html`
`
}
export function contactDetail (args) {
return render(contactDetailTemplate(args))
}
```
--------------------------------
### raw(value) / html.raw(value)
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Marks trusted HTML content to be inserted directly without escaping, ensuring that the provided HTML is rendered as-is.
```APIDOC
## `raw(value)` / `html.raw(value)`
Marks trusted HTML so it is inserted without escaping.
```js
html`
${raw('trusted')}
`
```
```
--------------------------------
### Toggle Boolean Attributes with fragtml
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Shows how to use the `?name=${condition}` syntax to conditionally add or remove boolean attributes like `disabled`.
```javascript
html``
```
--------------------------------
### Toggling Boolean Attributes
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Explains how to use the `?name=${condition}` syntax to toggle boolean attributes. The attribute is rendered if the condition is truthy, and omitted if falsey.
```javascript
render(html``)
```
--------------------------------
### RawHtml Class
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Represents HTML content that has been explicitly marked as trusted and will not be escaped during rendering.
```APIDOC
## `RawHtml`
Class returned by `raw(value)` and `html.raw(value)`.
```js
import { RawHtml, raw } from 'fragtml'
const trusted = raw('trusted')
trusted instanceof RawHtml
```
```
--------------------------------
### HtmlResult Class
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Represents the result of an `html` or `frag` tagged template, providing an object-oriented way to handle HTML output.
```APIDOC
## `HtmlResult`
Class returned by `html` and `frag` tagged templates.
```js
import html, { HtmlResult } from 'fragtml'
const result = html`
Hello
`
result instanceof HtmlResult
```
```
--------------------------------
### Recommended HtmlResult Class Shape
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Presents the recommended structure for the HtmlResult class, including private fields for compiled template, substitutions, and options, and methods for string conversion.
```javascript
class HtmlResult {
#compiled
#substitutions
#options
constructor (compiled, substitutions, options) {
this.#compiled = compiled
this.#substitutions = substitutions
this.#options = options
}
toString () {
return render(this)
}
valueOf () {
return render(this)
}
[Symbol.toPrimitive] () {
return render(this)
}
}
```
--------------------------------
### Composing Typed Template Functions
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
This approach uses function composition to create reusable, typed template functions for smaller pieces of UI. It offers stricter type checking at each composition boundary and is suitable when fragments need to be reused across multiple parent templates. The `render` function is used to render the output of these composed functions.
```typescript
import html, { render } from 'fragtml'
type InnerContext = {
text: string
}
type OuterContext = InnerContext & {
title: string
}
type FullContext = OuterContext & {
foo: string
}
export function inner (context: InnerContext) {
return html`
${context.text}
`
}
export function outer (context: OuterContext) {
return html`
${context.title}
${inner(context)}
`
}
export function full (context: FullContext) {
return html`
${context.foo}
${outer(context)}
`
}
render(inner({ text: 'Updated body text' }))
render(outer({
title: 'Outer section title',
text: 'Updated body text'
}))
render(full({
foo: 'Full page field',
title: 'Outer section title',
text: 'Updated body text'
}))
// @ts-expect-error outer requires both title and text.
render(outer({ text: 'Missing the outer title' }))
```
--------------------------------
### Escaping Script Tags
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Shows how FragTML automatically escapes potentially harmful HTML content like script tags when interpolating.
```javascript
render(html`
${''}
`)
// '
<script>alert(1)</script>
'
```
--------------------------------
### html Tagged Template
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
The `html` tagged template literal is the primary way to create HTML structures. It supports safe-by-default rendering and can be used with fragment IDs to select specific parts of a template.
```APIDOC
## `html`
Safe-by-default template tag.
```js
html`
${value}
`
```
Pass a fragment ID before the tagged template to render a selected fragment from that template:
```js
html('name')`...`
html({ fragmentId: 'name' })`...`
```
```
--------------------------------
### createHtml Alias Equivalence
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Confirms that `createHtml` is a strict alias of `html`, intended for use when the local tag must be named `html`.
```javascript
createHtml === html
```
--------------------------------
### Error Classes
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Provides specific error classes for handling issues related to fragment management, such as `DuplicateFragmentError`, `FragmentBoundaryError`, and `FragmentNotFoundError`.
```APIDOC
## Error classes
```js
import {
DuplicateFragmentError,
FragmentBoundaryError,
FragmentNotFoundError
} from 'fragtml'
```
```
--------------------------------
### Type Checking HtmlResult in TypeScript
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Illustrates how to use the `HtmlResult` class both at runtime and as a type in TypeScript, including a type guard function.
```typescript
import { HtmlResult } from 'fragtml'
import type { HtmlResult as HtmlResultType } from 'fragtml/types.js'
function sendHtml (result: HtmlResultType) {
return result.toString()
}
function isHtmlResultValue (value: unknown): value is HtmlResultType {
return value instanceof HtmlResult
}
```
--------------------------------
### JSDoc Typedefs for Fragtml
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Provides a set of JSDoc typedefs to define the types for substitutions, render options, and various callback functions used within the Fragtml library.
```javascript
/**
* @typedef {string | number | bigint | boolean | null | undefined} PrimitiveSubstitution
* @typedef {PrimitiveSubstitution | HtmlResult | RawHtml | FragmentBoundary | Substitution[]}
* @typedef {ReadonlyArray & { raw?: readonly string[] }} TemplateStrings
*
* @typedef {object}
* @property {string | undefined} [fragmentId]
*
* @callback HtmlTag
* @param {TemplateStrings} strings
* @param {...Substitution} substitutions
* @returns {HtmlResult}
*
* @callback RawHelper
* @param {unknown} value
* @returns {RawHtml}
*
* @callback FragmentBoundaryFactory
* @param {string} id
* @returns {FragmentBoundary}
*
* @typedef {object}
* @property {FragmentBoundaryFactory} start
* @property {FragmentBoundary} end
*
* @callback HtmlTagFactory
* @param {RenderOptions | string}
* @returns {HtmlTag}
*/
```
--------------------------------
### Escaping Untrusted User Input in Fragml
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Shows how Fragml automatically escapes ordinary strings to prevent untrusted content from being rendered as HTML.
```javascript
const userInput = ''
render(html`
${userInput}
`)
// '
<button>not trusted</button>
'
```
--------------------------------
### Fragment Boundary Symbol
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Defines a unique symbol for fragment boundary tokens to manage fragment support within the library.
```javascript
const fragmentBoundarySymbol = Symbol('fragtml.fragmentBoundary')
```
--------------------------------
### frag Alias
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
The `frag` function is an alias for `html`, providing flexibility for editor highlighting and repeated use by allowing assignment to a local tag name.
```APIDOC
## `frag`
Alias of `html`, useful when you want a local tag name for editor highlighting or repeated use:
```js
import { frag } from 'fragtml'
const html = frag(fragmentId)
```
Calling `html('name')` directly before a template can break editor HTML highlighting because the tag expression is no longer a simple identifier. Assign the result to a local tag name, or use the `/* html */` marker that Sublime Text and Zed understand:
```js
const h = frag(fragmentId)
return h/* html */`
${value}
`
```
```
--------------------------------
### Explicit Raw Insertion within Safe Tag
Source: https://github.com/bcomnes/fragtml/blob/master/plans/fragment-html-template-library.md
Illustrates using `html.raw` to insert trusted HTML content directly within a safe `html` tagged template. This allows mixing escaped and unescaped content in the same template.
```javascript
html`
${html.raw('trusted')}
`
// render(...) => '
trusted
'
```
--------------------------------
### Unsupported Quoted Boolean Attributes
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Demonstrates that quoted forms for boolean attributes are intentionally unsupported in v1.
```javascript
html``
html``
```
--------------------------------
### html.fragment.end
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Marks the end of the most recently opened fragment range, completing the definition of a renderable fragment.
```APIDOC
## `html.fragment.end`
Ends the most recently opened fragment range.
```js
${html.fragment.end}
```
```
--------------------------------
### Direct String Coercion of HTML Results
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Illustrates that the result object from html tag can be directly coerced to a string using String() or template literals.
```javascript
const result = html`
${'Hello'}
`
String(result)
result.toString()
`${result}`
```
--------------------------------
### Boolean Attributes
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Supports toggling boolean attributes in HTML elements using unquoted syntax, like `?name=${condition}`.
```APIDOC
## Boolean attributes
Use unquoted `?name=${condition}` syntax to toggle a boolean attribute.
```js
html``
```
```
--------------------------------
### Type Guards
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Provides public type guard functions to safely check the type of values, such as `isFragmentBoundary`, `isHtmlResult`, and `isRawHtml`.
```APIDOC
## Type guards
Use the public type guards to narrow unknown values without importing from internal `lib/` paths:
```js
import {
isFragmentBoundary,
isHtmlResult,
isRawHtml
} from 'fragtml'
```
```
--------------------------------
### Derive Full Argument Type for Template Implementation
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Derives the full argument type for the shared template implementation using FragmentTemplateArgs.
```typescript
type PageTemplateArgs = FragmentTemplateArgs
// Equivalent to:
// {
// fragmentId?: 'inner' | 'outer' | undefined
// context: {
// foo?: string
// title?: string
// text?: string
// }
// }
```
--------------------------------
### Check if a Value is a RawHtml Instance
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Verifies if a given variable is an instance of the `RawHtml` class, which is returned by `raw(value)` and `html.raw(value)`.
```javascript
import { RawHtml, raw } from 'fragtml'
const trusted = raw('trusted')
trusted instanceof RawHtml
```
--------------------------------
### TypeScript with Explicit Fragment-Name Union
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
This TypeScript snippet demonstrates how to use explicit fragment-name unions for type-checking fragment IDs and declared boundaries. It defines a `ContactFragment` type and uses it with `frag` and `RenderOptions`.
```typescript
import { frag, render } from 'fragtml'
import type { RenderOptions } from 'fragtml/types.js'
type ContactFragment = 'archive-ui' | 'details'
function contactDetailTemplate ({
contact,
fragmentId
}: {
contact: Contact
} & RenderOptions) {
const html = frag(fragmentId)
return html`
`
}
export function contactDetail (args: {
contact: Contact
} & RenderOptions) {
return render(contactDetailTemplate(args))
}
```
--------------------------------
### Handling Non-Printing Values
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Illustrates that null, undefined, booleans, and NaN values are omitted during interpolation, while 0 is rendered.
```javascript
render(html`
${null}${false}${Number.NaN}${0}
`)
// '
0
'
```
--------------------------------
### Check if a Value is an HtmlResult Instance
Source: https://github.com/bcomnes/fragtml/blob/master/README.md
Verifies if a given variable is an instance of the `HtmlResult` class, which is returned by `html` and `frag` tagged templates.
```javascript
import html, { HtmlResult } from 'fragtml'
const result = html`
Hello
`
result instanceof HtmlResult
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.