Skip to content

definePattern

Creates the render and args fields for a Storybook Meta object. Spread the return value into your default export to wire the Twig template and default story args.

Signature

ts
function definePattern(
  templateId: string,
  defaultArgs?: Record<string, unknown>,
): { render: (args: Record<string, unknown>) => string; args: Record<string, unknown> }

Parameters

ParameterTypeDescription
templateIdstringThe Twig namespace key for the template, in the form @{namespace}/{relative/path/_template.tpl.twig}. Must match a key registered in the template registry.
defaultArgsRecord<string, unknown>Default arg values for the story — same semantics as Storybook's args. Optional; defaults to {}.

Returns

An object with two keys:

  • render(args) — renders the template with the merged arg values and returns an HTML string
  • args — the defaultArgs object, passed through unchanged

Spread this into your Meta default export:

ts
export default {
  title: 'Atoms/Button',
  ...definePattern('@atoms/button/_button.tpl.twig', {
    button_text: 'Click me',
    button_color: 'primary',
  }),
} satisfies Meta;

Missing args behavior

Any arg key not present in the story's args returns null rather than undefined during rendering. This ensures twig.js |default(...) filters activate for missing values:

twig
{# PHP Twig: missing_var|default([]) returns [] ✓ #}
{# twig.js with null: null|default([]) returns [] ✓ #}
{# twig.js with undefined: undefined|default([]) returns '' ✗ (twig.js quirk) #}

Render errors

If twig.js throws during rendering (e.g. a template include fails to resolve), renderTwig returns a visible error block instead of propagating the exception:

html
<div style="color:red;..."><strong>Twig render error</strong> — @atoms/button/_button.tpl.twig

...error message...</div>

This keeps Storybook running when one pattern fails.

renderTwig

Low-level render function used internally by definePattern. Call this directly if you need to render a template outside of a story (e.g. in a decorator).

ts
function renderTwig(templateId: string, args: Record<string, unknown>): string

initTwig

Registers a template registry with twig.js and applies all shims (random, filter_truthy, source, short-ternary patch, macro hoisting). Called once by preview.ts at Storybook startup.

ts
function initTwig(registry: Record<string, string>): void

The registry argument maps namespace keys to raw template strings. The function is idempotent — calling it a second time is a no-op.

Released under the MIT License.