首页 > 解决方案 > 使用自定义函数扩展 twig-loader

问题描述

我在运行 Encore (webpack) 的 Symfony 5 应用程序中使用twig-loader包。在尝试通过 加载模板时twig-loader,我想扩展twig.js-functionality (由 loader 包使用)。

所以,基本上,我需要这个来运行:

// webpack.config.js
Encore.
  ...
  .addLoader({
      test: /\.twig$/,
      loader: 'twig-loader',
  })
  ...
;

module.exports = Encore.getWebpackConfig();


// somewhere in my js-file
const template = require('./form.html.twig');
template({
  'label': 'Some label',
});


// And the twig-file:
<form method="post" action="{{ path('example_route', {'some': 'parameter'}) }}">
    <button>{{ label }}</button>
</form>

在呈现上述内容时,我得到的错误path是 twig.js 不知道 -function:

Twig.Error {message: "path function does not exist and is not defined in the context", name: "TwigException", type: "TwigException", file: "$resolved:3132…b7d2:form.html.twig"}

有什么办法,我可以在全球范围内扩展twig.js功能,以便twig-loader使用我的扩展twig.js包?

标签: javascriptphpsymfonywebpacktwig

解决方案


由于在浏览器上运行时填充的模板,并且 twig 中的 path() 函数是服务器端函数(来自路由器组件),因此 path 不会像您预期的那样工作。

但是,由于您的路径是静态的,因此有一个简单的解决方案:将其作为变量传递给模板,从服务器端树枝传递,例如

<div id='my_data' data-example-path='{{ path('example_route') }}'></div>

如果您使用刺激,甚至更好,您可以将其作为变量传递给控制器​​。

如果您需要动态路径,请使用 fosjsrouting 包 ( https://github.com/FriendsOfSymfony/FOSJsRoutingBundle ),然后在您的 js 文件中创建路径,然后像以前一样将该路径传递给 twig 渲染器。

在 twig.js 中无法实现 path(),因为它无法访问路由表。


推荐阅读