> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.knapsack.cloud/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.knapsack.cloud/_mcp/server.

# Twig

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.

```bash
npm install @knapsack/renderer-twig
```

## Configure

```js
// knapsack.config.js
const { KnapsackTwigRenderer } = require('@knapsack/renderer-twig');

module.exports = configureKnapsack({
  // See full config options at https://github.com/knapsack-cloud/twig-renderer/blob/master/config.schema.json
  templateRenderers: [
    new TwigRenderer({
      src: {
        roots: ['./packages/twig'],
        namespaces: [
          {
            id: 'components',
            recursive: true,
            paths: ['./packages/twig/src'],
          },
        ],
      },
      alterTwigEnv: [
        {
          file: join(__dirname, './packages/twig/alter-twig.php'),
          // names of functions from this ^ file to execute
          functions: ['addCustomExtension'],
        },
      ],
    }),
  ]
  // ...
})
```

#### 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.