# @frctl/twig 中文文档

规范地址：https://npmcn.com/package/%40frctl/twig/

版本：1\.2\.13
npm 元数据更新时间：2022-08-17T18:45:06.024Z
中文译文更新时间：2026-11-15T13:16:38.747Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40frctl/twig
原文对照：https://npmcn.com/package/%40frctl/twig/?lang=original
项目主页：https://github.com/frctl/fractal/tree/main/packages/twig
源码仓库：https://github.com/frctl/fractal

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：23 kB，15 个文件
- 模块格式：CommonJS
- TypeScript 类型：未声明
- 运行依赖：3 个
- peer 依赖：@frctl/fractal ^1\.1\.0-beta\.1
- 首次发布：2016-08-29T09:58:24.038Z
- 最新版本发布：2022-08-17T18:45:05.855Z
- 近 30 天下载量：4390（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：25（近 12 个月 0 个）

## 中文简介

Fractal 的 Twig 模板适配器.

## 安装

```sh
npm install @frctl/twig
```

也可以使用：`pnpm add @frctl/twig`、`yarn add @frctl/twig`、`bun add @frctl/twig`

## README

# @frctl/t

[树枝](https://github.com/twigjs/twig.js) 模板嵌入适配器 [分形](http://github.com/frctl/fractal)。 。 。 .

[![NPM Version](https://img.shields.io/npm/v/@frctl/twig)](https://www.npmjs.com/package/@frctl/twig)

需要分形 v1.1.0 或 以上 .

要安装此适配器, 请运行此命令 :

`npm install @frctl/twig`

然后打开分形.js文件并添加以下行:

```js
/*
 * Require the Twig adapter
 */
const twigAdapter = require('@frctl/twig')();
fractal.components.engine(twigAdapter);
fractal.components.set('ext', '.twig');
```

## 文档使用 Twig

要对文件使用 Twig, 请设置文件引擎到 `@frctl/twig`数字 :

```js
fractal.docs.engine(twigAdapter);
```

## 以自定义配置扩展

```js
/*
 * Require the Twig adapter
 */
const twigAdapter = require('@frctl/twig')({
    // if pristine is set to true, bundled filters, functions, tests
    // and tags are not registered.
    // default is false
    pristine: false,

    // if importContext is set to true, all include calls are passed
    // the component's context
    // default is false
    importContext: false,

    // use custom handle prefix
    // this will change your includes to {% include '%button' %}
    // default is '@'
    handlePrefix: '%',

    // set a base path for twigjs
    // Setting base to '/' will make sure all resolved render paths
    // start at the defined components dir, instead of being relative.
    // default is null
    base: '/',

    // should missing variable/keys emit an error message
    // If false, they default to null.
    // default is false
    strict_variables: true,

    // define Twig namespaces, see https://github.com/twigjs/twig.js/wiki#namespaces
    // this may break some fractal functionality, like including components via their handles and the render tag
    namespaces: {
        'Components': './components'
    },

    // use twig.js default template loader
    // this will allow including templates via relative paths, like twig.js or PHP Twig does by default
    // changing this will break including components via their fractal handles
    // changing this will break the custom render tag
    // default is 'fractal'
    method: 'fs',

    // register custom filters
    filters: {
        // usage: {{ label|capitalize }}
        capitalize: function(str) {
            if (!str) return '';

            return str.charAt(0).toUpperCase() + str.slice(1);
        }
    },

    // register custom functions
    functions: {
        // usage: {{ capitalize(label) }}
        capitalize: function(str) {
            if (!str) return '';

            return str.charAt(0).toUpperCase() + str.slice(1);
        }
    },

    // register custom tests
    tests: {
        // usage: {% if label is equalToNull %}
        equalToNull: function(param) {
            return param === null;
        }
    },

    // register custom tags
    tags: {
        flag: function(Twig) {
            // usage: {% flag "ajax" %}
            // all credit to https://github.com/twigjs/twig.js/wiki/Extending-twig.js-With-Custom-Tags
            return {
                // unique name for tag type
                type: "flag",
                // regex match for tag (flag white-space anything)
                regex: /^flag\s+(.+)$/,
                // this is a standalone tag and doesn't require a following tag
                next: [ ],
                open: true,

                // runs on matched tokens when the template is loaded. (once per template)
                compile: function (token) {
                    var expression = token.match[1];

                    // Compile the expression. (turns the string into tokens)
                    token.stack = Twig.expression.compile.apply(this, [{
                        type:  Twig.expression.type.expression,
                        value: expression
                    }]).stack;

                    delete token.match;
                    return token;
                },

                // Runs when the template is rendered
                parse: function (token, context, chain) {
                    // parse the tokens into a value with the render context
                    var name = Twig.expression.parse.apply(this, [token.stack, context]),
                        output = '';

                    flags[name] = true;

                    return {
                        chain: false,
                        output: output
                    };
                }
            };
        }
    }
});

```

## 使用外部插件

要使用的示例 [树枝-js-标记下](https://github.com/ianbytchek/twig-js-markdown)数字 :

```js
const twigMarkdown = require('twig-markdown');
const instance = fractal.components.engine(twigAdapter);

// instance.twig refers to the twig.js instance
instance.twig.extend(twigMarkdown);

```

## 包含过滤器

### 路径

取出一个根相相通的路径,如果需要使其在静态的 HTML 导出中工作,则重新写入.

强烈建议您在需要链接到模板中的任何静态资产时使用此过滤器 .

路径参数应该从斜线开始,并与网根相对. 在静态 HTML 导出期间,此路径将被重写成相对当前页面的路径 .

用法 :

```twig
{{ '/css/my-stylesheet.css'|path }}
```

## 包含标签

### 提交

渲染标记使用提供给它的上下文数据制作一个组件(取自其手柄)。 如果不提供数据,它将使用组件配置文件中定义的上下文数据,如果它有一个.

用法 :

```twig
{% render "@component" with {some: 'values'} %}
```

## 常见问题

### @frctl/twig 是什么？

Fractal 的 Twig 模板适配器\.

### 如何安装 @frctl/twig？

在项目目录运行 npm install @frctl/twig，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@frctl/fractal（^1\.1\.0-beta\.1）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @frctl/twig 支持 TypeScript 吗？

该包的 package\.json 没有声明类型入口。需要类型提示时，可以在 npm 上查找社区维护的 @types/frctl\_\_twig 是否存在。

### @frctl/twig 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @frctl/twig 可以商用吗？

@frctl/twig 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @frctl/twig 的下载量有多少？

根据 npm 官方下载统计，@frctl/twig 在 2026/10/16 – 2026/11/14 这 30 天内被下载 4,390 次，日均约 146 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @frctl/twig 还在维护吗？

最新版本 1\.2\.13 发布于 2022/08/18（4 年前）；至今共发布 25 个版本，其中过去 12 个月发布了 0 个；首次发布于 2016/08/29。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

