Twig

Knapsack for Twig lets you develop and test components in isolation.
View as Markdown

Knapsack for Twig works by scanning your specified Twig code locations and automatically discovering reusable components, making them instantly available in your design system.

Why This Approach:

  • Zero Manual Work - Knapsack finds and configures your components automatically
  • 🔄 Always Current - Your documentation stays in sync with code changes
  • 🎯 Intelligent - Understands different export patterns and component structures
  • 🚀 Scale Effortlessly - Handle hundreds of components without individual setup

Requirements

  • Twig templates - Templates must be in Twig format
  • TwigRenderer configuration - Proper Twig setup required

Install

Requirements:

  • PHP 7.4 or later and Composer.
$npm install @knapsack/renderer-twig

Configure

1// knapsack.config.js
2const { KnapsackTwigRenderer } = require('@knapsack/renderer-twig');
3
4module.exports = configureKnapsack({
5 // See full config options at https://github.com/knapsack-cloud/twig-renderer/blob/master/config.schema.json
6 templateRenderers: [
7 new TwigRenderer({
8 src: {
9 roots: ['./packages/twig'],
10 namespaces: [
11 {
12 id: 'components',
13 recursive: true,
14 paths: ['./packages/twig/src'],
15 },
16 ],
17 },
18 alterTwigEnv: [
19 {
20 file: join(__dirname, './packages/twig/alter-twig.php'),
21 // names of functions from this ^ file to execute
22 functions: ['addCustomExtension'],
23 },
24 ],
25 }),
26 ]
27 // ...
28})

src

The src property defines the source directories and namespaces for your Twig templates. It ensures that Twig knows where to find the template files and how to organize them under specific namespaces.

  • roots An array of directories that serve as the root paths for your Twig templates. These directories are searched recursively.
  • namespaces An array of namespace objects, each containing:
    • id: A unique identifier for the namespace.
    • recursive: A boolean indicating whether to search for templates recursively within the specified paths.
    • paths: An array of directories within the root paths to include in the namespace.

alterTwigEnv

The alterTwigEnv property allows you to customize the Twig environment by adding extensions, functions, filters, or other customizations through PHP files.

  • file The path to the PHP file that contains the custom functions or extensions to add to the Twig environment.
  • functions An array of function names defined in the specified PHP file that should be executed to alter the Twig environment.