如何翻译数组项并将它们连接起来?

发布于 2024-12-25 22:22:17 字数 294 浏览 1 评论 0原文

使用 twig,如何翻译数组中的所有项目并用斜杠将它们连接起来? 我是否必须使用额外的变量或者是否有更聪明的方法?

目前,我正在做这样的事情:

{% set labels = [] %}
{% for feature in menu_item.features %}
  {% set labels = labels|merge([feature|trans([], 'features')]) %}
{% endfor %}
{{ labels | join(' / ')}}

这很糟糕。

Using twig, how can I translate all items in an array and join them with a slash?
Do I have to use an additional variable or is there a cleverer method?

For the moment, I'm doing something like this:

{% set labels = [] %}
{% for feature in menu_item.features %}
  {% set labels = labels|merge([feature|trans([], 'features')]) %}
{% endfor %}
{{ labels | join(' / ')}}

It sucks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

_失温 2025-01-01 22:22:17

也许我来晚了,但您现在可以使用地图过滤器轻松完成此操作:

{{ menu_item.features|map(feature => feature|trans)|join(' / ') }}

请参阅文档:

Maybe I'm late to the party, but you can now do this easily with the map filter:

{{ menu_item.features|map(feature => feature|trans)|join(' / ') }}

See documentation:

残月升风 2025-01-01 22:22:17

为什么不在循环时输出内容呢?

{% for feature in menu_item.features %}
  {% if loop.index0 > 0 %}/{% endif %}
  {{feature|trans}}
{% endfor %}

Why not just output the content while you're looping ?

{% for feature in menu_item.features %}
  {% if loop.index0 > 0 %}/{% endif %}
  {{feature|trans}}
{% endfor %}
浮生面具三千个 2025-01-01 22:22:17

并非所有事情都应该在“视图”内完成。

这种类型的代码可能更好地放置在控制器逻辑中,然后作为合并+连接的结果传递到视图中。因为在您的示例中,您所做的只是编译结果,这可以在代码中更轻松地完成。

Not everything should be done within the "view".

This type of code is probably much better placed within your controller logic and then passed into the view as the merged+joined result. Because in your example all you're doing is compiling a result which can much more easily be done within code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文