javascript - 使用自定义函数扩展 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
包?
解决方案
由于在浏览器上运行时填充的模板,并且 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(),因为它无法访问路由表。
推荐阅读
- python - 独立 Django 应用程序中没有名为“django”的模块
- python - PySide QtGui.QListWidget:如何关联到对象数据
- c# - DotNetBrowser:在选项卡之间切换
- javascript - 我无法从反应组件值设置状态
- c++ - 命名空间函数中的C++ lambda?
- linux - 在最后一次出现模式后使用 sed 删除特定行
- excel - 当提示用户在 Excel 中使用输入框选择范围时,强制 VBA 显示当前选定的单元格
- python - 在 Python 中,如何用字符串切片?
- azure-powershell - 在 Azure powershell 中获取 webapp 的受限 ip
- r - 匹配数据框和向量的行时如何提取列索引