Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert variable to string in Twig

Tags:

twig

symfony

I'm having trouble to translate a string in Twig. I'm building a theme for a multilingual webshop.

A user can create a USP (Unique Selling Point). 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".

To translate a string in the system you have to use a {{ 'Free shipping' | t }} filter.

Is there any way to get {{ theme.usp }} translated. I thought this would be useful but I don't know how to incorporate this. How to concatenate strings in twig

What I did was:

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

Doing this gives me an error since {{ theme.usp }} has to be between ''. Doing that doesn't gives me 'Free shipping' as outcome but 'theme.usp'.

Anyone a suggestion?

like image 713
Meules Avatar asked Jul 23 '14 09:07

Meules


2 Answers

Try:

{{ theme.usp|trans }}

or if it must be filtered by t then

{{ theme.usp|t  }}
like image 79
4 revs, 2 users 93% Avatar answered Nov 19 '22 09:11

4 revs, 2 users 93%


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.

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. 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. Yeah, it's another missing functionality in Symfony2, btw.

like image 25
forsberg Avatar answered Nov 19 '22 08:11

forsberg