外部 JS 文件中的 Twig 变量
我想外部化我的 JS 代码,但代码中有 Twig 变量。
你有什么技巧可以让它发挥作用?
team: {{ 'Select your team'|trans }}
I would like to externalize my JS code, but there is Twig variable in the code.
What are your tricks to make this working?
team: {{ 'Select your team'|trans }}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您需要将 twig 变量传递到外部 javascript 文件时,有两种方法
对于这种方法,我通常在我的主/基本模板中添加一个名为“javascript”块的块
base.twig.html
page.html.twig
data-*
属性将变量传递给 javascript旁注:如果你想传递一个对象或一个数组 该过滤器会将变量转换为有效的 javascript 对象
twig
您始终可以使用json_encode
过滤器,如果您想控制公开哪些对象属性, json_encode
过滤器,您始终可以实现接口Serialized
There a two approaches when you need to pass a twig variable to an external javascript file
For this approach I usally add a block called "javascript" block in my main/base template
base.twig.html
page.html.twig
data-*
attributesSidenote: if you want to pass an object or an array to
twig
you can always use thejson_encode
filter, which will convert the variable to a valid javascript objectIf you want to have control over which object properties are exposed by the
json_encode
filter you can always implement the interfaceSerializable