npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@pdrittenhouse/storybook-addon-twig-wordpress

v0.1.5

Published

Storybook addon for rendering Twig patterns with @namespace resolution — built for WordPress/Timber themes.

Readme

@pdrittenhouse/storybook-addon-twig-wordpress

Storybook addon for rendering Twig patterns with @namespace resolution — built for WordPress/Timber themes.

npm License: MIT

Features

  • Renders _*.tpl.twig pattern templates in the browser using twig.js
  • Configurable @namespace alias resolution — map any prefix to a pattern directory
  • Parent/child pattern cascade via extraPatternRoots — last entry wins
  • Compiled SCSS variables JSON injected into every story under a configurable key (default: sass_data)
  • WordPress/Timber context mock (site, options, menus, widgets) available in every story
  • Automatic shims for twig.js incompatibilities (random(), source(), arrow-function |filter, short-ternary)
  • Contextual color select control helper via colorArgType()
  • Vite-first with webpack fallback

Installation

npm install --save-dev @pdrittenhouse/storybook-addon-twig-wordpress

Peer dependencies: storybook ^8.0.0 || ^10.0.0, @storybook/html ^8.0.0 || ^10.0.0

Quick start

.storybook/main.ts

import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');

export default {
  framework: { name: '@storybook/html-vite', options: {} },
  addons: [
    {
      name: '@pdrittenhouse/storybook-addon-twig-wordpress',
      options: {
        patternsRoot: path.join(ROOT, 'src/patterns'),
        namespaces: {
          atoms:     'atoms',
          molecules: 'molecules',
          organisms: 'organisms',
        },
        // Optional: expose compiled SCSS variables as sass_data in every story
        scssVariablesPath: path.join(ROOT, 'dist/scss-variables.json'),
        // Optional: forward global SCSS variables to pattern stylesheets
        sassAdditionalData: `@use "${path.join(ROOT, 'src/patterns/_variables.scss').replace(/\\/g, '/')}" as *;`,
      },
    },
  ],
  stories: ['../src/patterns/**/*.stories.ts'],
};

src/patterns/atoms/button/button.stories.ts

import type { Meta, StoryObj } from '@storybook/html';
import { definePattern } from '@pdrittenhouse/storybook-addon-twig-wordpress';

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

export const Default: StoryObj = {};
export const Secondary: StoryObj = { args: { button_color: 'secondary' } };

WordPress parent/child cascade

For WordPress parent/child theme setups, use patternsRoot for the parent theme and extraPatternRoots for the child. Child entries in extraPatternRoots override parent patterns at the same relative namespace path — last entry wins.

// child theme .storybook/main.ts
addons: [{
  name: '@pdrittenhouse/storybook-addon-twig-wordpress',
  options: {
    patternsRoot:      path.join(PARENT_THEME, 'src/patterns'), // parent patterns
    extraPatternRoots: [
      path.join(ROOT, 'src/patterns'), // child overrides parent
    ],
    macrosRoot:       path.join(PARENT_THEME, 'src/macros'),
    extraMacrosRoots: [path.join(ROOT, 'src/macros')],
  },
}],

extraPatternRoots accepts any number of roots — useful if your theme pulls from a shared pattern library in addition to a parent theme.

Story deduplication (child wins over parent) requires explicit file lists in your stories array. See the pattern cascade guide for the findStoryFiles() helper pattern.

Configuration

| Option | Type | Required | Description | |--------|------|----------|-------------| | patternsRoot | string | ✓ | Absolute path to your primary patterns root. | | namespaces | Record<string, string> | ✓ | Maps namespace names to subdirectory names under patternsRoot. Keys become the @namespace prefix in Twig {% include %}/{% embed %} tags. | | extraPatternRoots | string[] | — | Additional pattern roots (parent/child theme). Later entries override earlier keys — last in wins. | | macrosRoot | string | — | Absolute path to your primary macros root. All .twig files are registered under the @macros/ prefix. | | extraMacrosRoots | string[] | — | Additional macros roots. Later entries override earlier keys. | | scssVariablesPath | string | — | Absolute path to scssVariables.json. Parsed and exposed as sass_data in every story's render context. | | sassAdditionalData | string | — | SCSS additionalData injected before every .scss file import. Use the same @use barrel as your webpack build. | | templateGlob | string | — | Filename glob for template files to register. Supports * wildcard. Default: '_*.tpl.twig' | | globalContext | Record<string, unknown> \| false | — | Context merged into every story's args. Pass false to disable. Default: minimal WordPress/Timber mock. |

API

definePattern(templateId, defaultArgs?)

Creates the render and args fields for a Storybook Meta object. Spread into your default export.

import { definePattern } from '@pdrittenhouse/storybook-addon-twig-wordpress';

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

| Parameter | Type | Description | |-----------|------|-------------| | templateId | string | Twig namespace key: @{namespace}/{relative/path/_template.tpl.twig} | | defaultArgs | Record<string, unknown> | Default arg values — same semantics as Storybook's args |

colorArgType(colors?) / CONTEXT_COLORS / ContextColor

Renders a contextual-color field as a select control in Storybook's Controls panel. Accepts an optional colors array to override the default CONTEXT_COLORS list for a specific field.

import { definePattern, colorArgType } from '@pdrittenhouse/storybook-addon-twig-wordpress';
import type { ContextColor } from '@pdrittenhouse/storybook-addon-twig-wordpress';

export default {
  title: 'Atoms/Button',
  ...definePattern('@atoms/button/_button.tpl.twig'),
  argTypes: {
    // use addon-configured context colors (default)
    button_color: colorArgType(),
    // use a custom color list
    brand_color: colorArgType(['red', 'blue', 'green']),
  },
  args: {
    button_color: 'primary' satisfies ContextColor,
  },
} satisfies Meta;

CONTEXT_COLORS is the full readonly array of valid values if you need it directly. ContextColor is the TypeScript union type.

renderTwig(templateId, args) / initTwig(registry)

Lower-level functions for custom render implementations. definePattern wraps both — reach for these only when you need direct control.

WordPress context

The addon injects a WordPress/Timber context into every story's render args by default. Templates can reference site, options, menus, and widgets the same way they do in WordPress.

The default context has empty values. Configure globalContext in main.ts to provide real values for your project:

options: {
  globalContext: {
    site: { name: 'My Theme', url: 'http://localhost', description: '', language: 'en-US' },
    options: {},
    menus: {},
    widgets: {},
  },
}

sass_data (the parsed contents of scssVariablesPath) is also merged in automatically alongside the context.

Pass globalContext: false to opt out entirely for non-WordPress Twig projects.

Override any field at the story level via args — story args always win.

twig.js compatibility

The addon ships several shims and compile-time patches for PHP Twig syntax that twig.js 1.x does not support:

| PHP Twig feature | How it's handled | |-----------------|-----------------| | random() | Shim registered via extendFunction — returns a random integer (0–n), random array element, or random string character matching PHP Twig's behaviour | | \|filter(v => v) | Arrow-function syntax preprocessed to \|filter_truthy before template registration | | function('php_fn') | Replaced with '' at preprocess time — prevents "function does not exist" errors | | {% import _self %} with trailing macros | Macro blocks hoisted to top of template before import tag so they're defined before use | | Short ternary a ? b (no :) | twig.js 1.x runtime bug patched at compile and parse time via Twig.extend() | | source('path') | Returns SVG content from a build-time window.__svgSourceRegistry or synchronous XHR fallback |

Patterns must use _name.tpl.twig naming (leading underscore). Only files matching this pattern are registered in the twig.js template registry.

Requirements

  • Node.js 18+
  • Storybook 8 or 10
  • @storybook/html + @storybook/html-vite

License

MIT © P.D. Rittenhouse