Translate the value of twig variable - symfony

Is it possible to translate the value of twig variables in a template with the 'trans' tag?
Say for instance I am passing a product to my template. This product has a definition with a trans tag e.g {{ product.definition|trans }}. This definition could either be in EN or DE or some other language. How could I translate the definition.

What are you trying to do is not a good way, It would look like this:
messages.en.yml
product:
definition:
some_value1: Some value 1
some_value2: Some value 2
and in template, you would do something like this:
{% set definition_value = product.definition %}
{% set trans_definition = 'product.definition.' ~ definition_value %}
{{ trans_definition|trans }}
it'll work, if it finds the key. What if it cant find it?
That's why you should use DoctrineBehaviors from KnpLabs, which handles all the dynamic translations for you..

If {{ product.definition }} equals 'cellphone' the following should work.
message.language.yml:
'cellphone': This will work!
However if you want to map it with the 'product' key in your message file like this:
product:
'cellphone': This also works
add the key to the twig template like so:
{{('product.'~product.definition)|trans }}

Related

Passing all parameters as array and changing one of them

I am passing an array of get arguments from controller to twig template, and then create a link:
{{ url('route_name', array_of_get_parameters) }}
It works, but what if I want to pass all BUT ONE of those parameters unchanged? Something like:
{{ url('route_name', array_of_get_parameters, {'param1': 'value'}) }}
The example above doesn't work of course...is there a way to do this?
Use twig merge filter like this:
{{ url('route_name', array_of_get_parameters|merge({'param1': 'value'})) }}
You cannot do this.
Instead override the value in the controller (<- better) or in the twig template, before the url generation.

Keep leading 0 in Twig

In my database, I have a field containing the following data : 000010 (the type is integer)
In my twig tpl, I want to display it, then I do : {{ spending.documentName }}
But the browser displays "10". As if Twig was automaticcaly performing a trim on my data.
I tried {{ spending.documentName|raw }} but it doesn't work. I dont find anything on Google about how to keep leading 0 with Twig.
Does anyone know how to proceed ?
I think you must force the format (as your type is integer).
You can use the format filter :
{{ "%06d"|format(spending.documentName) }}
Or better create a twig extension (http://symfony.com/doc/current/cookbook/templating/twig_extension.html):
public function strpad($number, $pad_length, $pad_string) {
return str_pad($number, $pad_length, $pad_string, STR_PAD_LEFT);
}
It's clearer in your template :
{{ spending.documentName | strpad(6,'0') }}
You need to use the format filter.
Since placeholders follows the sprintf() notation, you should be able to convert sprintf('%06d', $integer); in PHP to {{ '%06d'|format($integer) }} in Twig.
Kinda late here, but ran into the same.
With twig 3.x you can use:
{{your.number | format_number({min_integer_digit:'2'})}}

Pass variables to Twig Translator

In messages.en.yml:
variable_name: Welcome to %site_name% - %other_info%
In Twig
{{ 'variable_name'|trans( -here- ) }}
It's the -here- part I'm struggling to know how to pass data in. I must do it this way (above is just an example).
Maybe I'm misunderstanding the question but if I understand correctly, you only need to give an array as the first parameter of the trans filter.
{{ 'variable_name'|trans({'%site_name%': 'My Website'}) }}
And of course, values can be variables if you don't put them between quotes :
{{ 'variable_name'|trans({'%site_name%': 'My Website', '%other_info%': page_name}) }}

Symfony2 transchoice tag

I have added the translator service for my Symfony2 project. I use it both in controllers and in twig templates. It's configured fine and all the {% trans %} tags work as they mean to. But in some cases I need to use the {% transchoice %} tag, and it's not getting the translation. Here is an example from my code.
{% transchoice post['comments']['count'] %}
{0} Comments| {1} Comment| ]1,Inf] Comments
{% endtranschoice %}
Also have tried writing this in one line.
I get the correct choice for the comment count, but the word itself is not beeng translated. Like the translator is not able to find the corresponding translation. In the messages.de.yml I have
Comment: "Kommentar"
Comments: "Kommentare"
Is it something wrong with my transchoice syntax? Maybe I need to place spaces somewhere, or anything like that?
In your translation file, you should write this:
{0} Comments| {1} Comment| ]1,Inf] Comments: "{0} Kommentare| {1} Kommentar| ]1,Inf] Kommentare"
UPDATE:
An xliff example that works for me :
<trans-unit id="search.results.summary">
<source>search.results.summary</source>
<target>{0}Pas d'annotations trouvée pour "%search_text%"|{1}Une annotation trouvée pour "%search_text%"|]1,Inf]%search_count% annotations trouvées pour "%search_text%"</target>
</trans-unit>
How I use it:
<h2>{{ 'search.results.summary' | transchoice(search_count, {
'%search_text%': search_text,
'%search_count%': search_count}) }}</h2>
As you see, I don't use the complicated notation as the source for my translation, since it is pretty useless and would make the template less readable. Instead, I put a dot-separated string representing the semantical value of my string.
In your case, I guess the correct thing to use would be something like this:
comment.summary: "{0} Kommentare|{1} Kommentar|]1,Inf] Kommentare"
and
{% transchoice post['comments']['count'] %}
'comment.summary'
{% endtranschoice %}
Good luck.

Symfony 2 + Twig global variables

How can one get a twig global variable to maintain modification after changing it with includes? My desired output is "set # deeper" though I get "original setting".
app/config/config.yml
twig:
globals:
testvar: "original setting"
root.html.twig
{% include "MyBundle::levelone.html.twig" %}
{{ testvar }}
levelone.html.twig
{% set testvar = "set # levelone" %}
{% include "MyBundle::deeper.html.twig" %}
deeper.html.twig
{% set testvar = "set # deeper" %}
From a container aware object :
$this->get('twig')->addGlobal('ThomasDecauxIsAwsome', 4);
Interesting question and I don't know an answer but no amount fooling around with blocks and stuff will work. I looked in the generated php cache template files. When you echo a variable it looks like:
// {{ testvar }}
echo twig_escape_filter($this->env, $this->getContext($context, "testvar"), "html", null, true);
So basically it first looks for testvar in your local context. If not found then it looks in the global context.
When you set the value of test var you get:
// {% set testvar = 'level one' }}
$context["testvar"] = "level one";
So only the local context gets updated. The changed value goes away when the included template returns.
So by default at least it looks like global variables are really read only.
It might be possible to do this through an extension. I don't know enough about the internals.
Have you tried to define a global variable through Twig? You can do it in your config.yml file as follows:
twig:
globals:
my_global_var : myvalue
So {{my_global_var}} in your template will print myvalue
For more info read the official docs.
It's possible by defining a Twig Extension via Services, check here

Resources