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 🙏

© 2024 – Pkg Stats / Ryan Hefner

storybook-framework-template-engine

v0.0.2

Published

Storybook for Templating Engines: View templated snippets in isolation with Hot Reloading.

Downloads

475

Readme

Storybook for Templating Engines


Storybook for Templating Engines is a UI development environment for your template snippets (e.g. using LiquidJS or Nunjucks). With it, you can visualize different states of your UI components and develop them interactively.

Storybook Screenshot

Storybook runs outside of your app. So you can develop UI components in isolation without worrying about app specific dependencies and requirements.

🚀 Getting Started

Follow Storybook's setup instructions.

Install this framework:

# Using your configured package manager (e.g. npm, yarn or pnpm)
npm install storybook-framework-template-engine --save-dev

Once installed, a couple of steps are required to get your templating engine to parse and render templates.

Step 1

💡 The following examples are for LiquidJS, the specific implementation will vary depending on the templating engine.

A render function parameter needs to be configured for your templating engine. For convenience you can do this setting global parameters:

// .storybook/preview.js

// Import your template engine - in this case LiquidJS
import { Liquid } from 'liquidjs';

const engine = new Liquid({
  root: 'templates', // Relative to `/src`
  extname: '.liquid', // Allows omission of `.liquid` extension
});

export const parameters = {
  templateEngine: {
    // Receives the story template and args which can be passed to renderer
    render: (template, args) => engine.parseAndRender(template), // Returns Promise (async)

    /*
      // Nunjucks example (@see: https://mozilla.github.io/nunjucks/api.html#renderstring)
      render: (template, args) => nunjucks.renderString(template, args),
    */
  },
};

💡 Note: it might be worth configuring the engine in a separate file which can then be shared with a Webpack loader.

Step 2

Configure Storybook to expose templates as static files:

// .storybook/main.js

module.exports = {
  // Set framework
  framework: 'storybook-framework-template-engine',

  // ...other config...

  staticDirs: [
    // Expose templates as static files
    {
      from: '../src/templates',
      to: '/templates', // Match with root input to the template engine
    },
  ],
};

🖋 Write Stories

Stories need to return a string which is then passed to the function provided to parameters.templateEngine.render().

// stories/Button.stories.js
export default {
  title: 'Example/Button',
};

// Return a string to be passed to the render function
export const Default = () => `<button>My Button</button>`;

Loading Templates

However, this particular example is of little use on it's own as it's not really using the templating engine we've configured.

Let's create a template file (using the example LiquidJS):

<!-- src/templates/button.liquid -->
<button>{{ label | default: 'My Button' }}</button>

Liquid allows us to render templates using the render tag.

// stories/Button.stories.js
export default {
  title: 'Example/Button',
};

// Return a string of Liquid markup
export const Default = () => `{% render 'button' %}`;

The string is then parsed by Liquid and the render tag tells Liquid to fetch the template, of which we have exposed using Storybook's staticDirs.

Passing Parameters

We can make the templates integrate with Storybook's controls by forwarding the arguments to the render tag:

// stories/Button.stories.js
export default {
  title: 'Example/Button',
  argTypes: {
    label: { control: 'text' },
  },
};

// Return a string of Liquid markup
export const Default = (args) => `{% render 'button', label: ${args.label} %}`;
Default.args = {
  label: 'Custom Label',
};

💪 Optional: Docs Source Code Override

To see how the templates can be used in your actual project (as in, the one Storybook is supporting), you can override docs source to show template provided to render function.

// stories/Button.stories.js
export default {
  title: 'Example/Button',
  argTypes: {
    label: { control: 'text' },
  },
};

// Return a string of Liquid markup
export const Default = (args) => `{% render 'button', label: ${args.label} %}`;
Default.args = {
  label: 'Custom Label',
  docs: {
    // Override source code output for `Docs` addon
    transformSource(snippet, story) {
      return `{% render 'button', label: ${story.parameters.label} %}`;
    },
  },
};

🦾 Upgrade: Render Template Function

Taking this concept even further, we can simplify our story writing by creating a utility function which provides the render code and forwards the arguments automatically:

// stories/utils.js
import { escape, isString } from 'lodash-es';

/**
 * Use in place of `Template.bind({})` to generate a Template and automatically
 * provide `transformSource` to override the docs.
 */
export const bindRenderTemplate = (templateName) => {
  const Template = (args) => createRenderTemplate(templateName, args);

  Template.parameters = {
    docs: {
      ...(Template.parameters?.docs ?? {}),
      transformSource(snippet, story) {
        return createRenderTemplate(templateName, story.parameters.args);
      },
    },
  };

  return Template;
};

/**
 * Create LiquidJS render code with provided arguments.
 */
export const createLiquidRenderTemplate = (templateName, args) => {
  const argEntries = Object.entries(args);

  return `{% render '${templateName}'${argEntries.length ? ', ' : ''}${argEntries
    .map(([k, v]) => `${k}: ${isString(v) ? `'${escape(v)}'` : JSON.stringify(v)}`)
    .join(', ')} %}`;
};
// stories/Button.stories.js

import { bindRenderTemplate } from '../utils';

export default {
  title: 'Example/Button',
  argTypes: {
    label: { control: 'text' },
    primary: { control: 'boolean' },
  },
};

const templateName = 'button';

export const Primary = bindRenderTemplate(templateName);
Primary.args = {
  label: 'Primary Button',
  primary: true,
};

export const Secondary = bindRenderTemplate(templateName);
Secondary.args = {
  label: 'Secondary Button',
};