简体   繁体   English

在Twig中将变量转换为字符串

[英]Convert variable to string in Twig

I'm having trouble to translate a string in Twig. 我在Twig中翻译字符串时遇到了麻烦。 I'm building a theme for a multilingual webshop. 我正在为多语种网店建立一个主题。

A user can create a USP (Unique Selling Point). 用户可以创建USP(唯一销售点)。 Problem is that it won't translate when you have a different language. 问题是当你有不同的语言时它不会翻译。

So the usp is called like this in the template {{ theme.usp }} The outcome of that is for example "Free shipping". 所以在模板{{ theme.usp }}就像这样调用usp。结果就是例如“免费送货”。

To translate a string in the system you have to use a {{ 'Free shipping' | t }} 要翻译系统中的字符串,您必须使用{{ 'Free shipping' | t }} {{ 'Free shipping' | t }} filter. {{ 'Free shipping' | t }}过滤器。

Is there any way to get {{ theme.usp }} translated. 有没有办法让{{ theme.usp }}翻译。 I thought this would be useful but I don't know how to incorporate this. 我认为这会很有用,但我不知道如何将其合并。 How to concatenate strings in twig 如何在twig中连接字符串

What I did was: 我做的是:

{% set usp = {{ theme.usp }} %}
{{ usp | t }}

Doing this gives me an error since {{ theme.usp }} has to be between '' . 这样做会给我一个错误,因为{{ theme.usp }}必须在''之间。 Doing that doesn't gives me 'Free shipping' as outcome but 'theme.usp' . 这样做不会给我'Free shipping'作为结果,但'theme.usp'

Anyone a suggestion? 有人建议吗?

Try: 尝试:

{{ theme.usp|trans }}

or if it must be filtered by t then 或者如果必须用t过滤

{{ theme.usp|t  }}

Easy way to do this is to use one of filters (which are in fact PHP functions at the end) that simply returns string as in PHP docs. 简单的方法是使用一个过滤器(最后是PHP函数),它只返回PHP文档中的字符串。

For example, I had a problem with explicitly setting a value in a choice (SELECT/OPTION) form type, as it required a string, but I got an int as a value. 例如,我在选择 (SELECT / OPTION)表单类型中显式设置值时遇到问题,因为它需要一个字符串,但我得到一个int作为值。 I simply did this: 我只是这样做:

{{ form_widget(form.scope, {'value': scope|trim}) }}

scope was int, but trim (and other PHP functions, here as Twig filters) automatically makes it a string. scope是int,但trim(和其他PHP函数,这里作为Twig过滤器)自动使它成为一个字符串。 Yeah, it's another missing functionality in Symfony2, btw. 是的,它是Symfony2中的另一个缺失的功能,顺便说一句。

Try this 试试这个

{{ usp|print_r }}

It worked for me. 它对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM