Twig include : use translation in the passed argument - php

This works fine
{% include 'site/snippet.html.twig'
with {'description': 'Some text'}
%}
But how to get this to work? Using a translation as argument
{% include 'site/snippet.html.twig'
with {'description': '{{ 'solutions.description' | trans }}'}
%}
The snippet.html content is:
<p>
{{ description }}
</p>
And calling the translation {{ 'solutions.description' | trans }} alone shows the content as expected.
What syntax would it be?

You don't need to wrap the string in an extra set of {{ }}. Actually it should work like:
with {'description': 'solutions.description'|trans}

Related

Identifying white space in a twig variable

I have a situation where I need to identify if there is a blank space in a variable in a twig template, and to treat it slightly differently.
Given names in this application are stored with middle initials in the given name field; they are not stored separately.
What I'm trying to achieve is this: Typically most given names are one word, e.g. "John" or "Susan" or something similar. In some of these cases we have cases where the middle initial is stored within this variable (e.g. John J)
Following standard citation standards, we need to be able to list items like this:
{{ surname }}, {{ given_name }}, ed.
This way it would appear like "Smith, John, ed." This is normally fine, however in some situations, where there is a middle initial, it appears as "Smith, John J, ed." - this is incorrect. I can't add a period after the given name, as "Smith, John., ed" would be an incorrect citation standard.
What I'm trying to do is to identify if a given_name contains a space, followed by a single letter, and then format it differently.
Something like this:
{% if given_name [has a blank space preceding a single letter] %}
{{ given_name }}., ed.
{% else %}
{{ given_name }}, ed.
{% endif %}
Is there a way to do this with regex within twig, or is there another method?
Thanks in advance
We can translate your requirement:
has a blank space preceding a single letter
In this little algorithm:
{% set given_name = 'John J' %}
{% set given_name_elems = given_name|split(' ') %}
{% set size = given_name_elems|length %}
{% if size >0 and given_name_elems[size-1]|length == 1%}
{ given_name }}., ed.
{%else%}
{{ given_name }}, ed.
{%endif%}
I suggest you to incapsulate this logic in a function or in a macro.
You could made some try in this working example
This is possible, but is not necessarily going to handle edge cases well. Assuming that you need to do the whole thing in twig, you could do something like this:
{% set nameArray = given_name | split(' ') %}
{% set first_name = nameArray[0] %}
{% set middle_initial = nameArray[1] is defined ? " "~nameArray[1]~"." : ""%}
At this point `middle_initial is now set to either an empty string or the middle initial with the period so you can output the full name like:
{{ surname }}, {{first_name ~ middle_initial}}, ed
You could use a regex with the matches comparison operator and add the dot if given_name matches the pattern.
{{ given_name }}{% if given_name matches '/^.+ .$/' %}.{% endif %}
Sorry, I didn't give you a good answer initially. I've updated my code and my twigfiddle. It's a bit simpler than #Matteo 's:
{% set given_name = 'John J' %}
{% set nameArray = given_name|split(' ') %}
{% if nameArray[1] is defined %}
{{ nameArray[0] }} {{ nameArray[1] }}., ed.
{% else %}
{{ nameArray[0] }}, ed.
{% endif %}
Where {{ nameArray[0] }} specifies the first element of the array. If nameArray1 contains anything, then it is defined.
Here is a working twigfiddle to show you it works.

Twig Array to string conversion

This is probably relatively easy to do, but I'm new to twig and I'm frustrated.
I'm adapting code from this answer: https://stackoverflow.com/a/24058447
the array is made in PHP through this format:
$link[] = array(
'link' => 'http://example.org',
'title' => 'Link Title',
'display' => 'Text to display',
);
Then through twig, I add html to it, before imploding:
<ul class="conr">
<li><span>{{ lang_common['Topic searches'] }}
{% set info = [] %}
{% for status in status_info %}
{% set info = info|merge(['{{ status[\'display\'] }}']) %}
{% endfor %}
{{ [info]|join(' | ') }}
</ul>
But I'm getting:
Errno [8] Array to string conversion in
F:\localhost\www\twig\include\lib\Twig\Extension\Core.php on line 832
It's fixed when I remove this line, but does not display:
{{ [info]|join(' | ') }}
Any ideas how I can implode this properly?
** update **
Using Twig's dump function it returns nothing. It seems it's not even loading it into the array in the first place. How can I load info into a new array.
info is an array, so you should simple write
{{ info|join(', ') }}
to display your info array.
[info] is a array with one value : the array info.
You shouldn't really be building complex data structures inside of Twig templates. You can achieve the desired result in a more idiomatic and readable way like this:
{% for status in status_info %}
{{ status.display }}
{% if not loop.last %}|{% endif %}
{% endfor %}
You can user json_encode for serialize array as strig, then show pretty - build in twig
{{ array|json_encode(constant('JSON_PRETTY_PRINT')) }}
if need associative array:
{{info|json_encode(constant('JSON_PRETTY_PRINT'))|raw}}

(CakePHP 2.x) $this->assign() with twig

Hi how use this part of code with twig,
$this->assign('title', 'Home');
not
echo $this->assign('title', 'Home');
I tried,
{% set assign = ('title', 'Home') %}
{% set this.assign = ('title', 'Home') %}
{% set assign = {'title', 'Home'} %}
{{ assign('title', 'Home') }}
But still don't work
Thanks you
I don't know about using $this in the context of a template (it would refer to some generated class instance), but you can perform arbitrary operations without printing by using the do statement.
The do tag works exactly like the regular variable expression ({{ ... }}) just that it doesn't print anything:
{% do 1 + 2 %}
To access the view itself when using TwigView, use the _view variable:
{% do _view.assign('title', 'Home') %}

Concatenation with dynamic variables for Twig symfony

I have a specific problem with concat of twig.
When I trying to concatenate dynamic variables showing the error.
Here is my code :
{% set i = 0 %}
{% set nbLignes = codeEvt.nb_lignes_~i %}
{% set nbLignesRef = codeEvt.nb_lignes_ref_~i %}
But I have this error message :
Method "nb_lignes_" for object "\DTO\SuiviJourFonc" does not exist in XXXXXXXXX.html.twig at line 211
I would like to take codeEvt.nb_lignes_0 , but i would like build a "for" for others variables like nb_lignes_1, nb_lignes_2 , nb_lignes_3 ...
How can i do this ?
attribute can be used to access a dynamic attribute of a variable:
The attribute function was added in Twig 1.2.
{{ attribute(object, method) }}
{{ attribute(object, method,arguments) }}
{{ attribute(array, item) }}
Try like this,
{{ attribute(codeEvt, 'nb_lignes_ref_' ~ i) }}
You can try the array-like notation:
{{ codeEvt['nb_lignes_ref_' ~ i] }}
Or even use string interpolation:
{{ codeEvt["nb_lignes_ref_#{i}"] }}

preg_match in twig

First of all, I know that the logic should be in the controller and not in the view and I keep it that way.
But in this particular situation I need to use preg_match within a ternary operation to set the css class of a div.
Example:
{% for list in lists %}
<div class="{{ (preg_match(list.a, b))>0 ? something : else }}"...>...</div>
{% endfor %}
How can I achieve the (preg_match(list.a,b))>0 condition in twig?
Thanks in advance
For those who came here from Google search results (like me).
There's containment operator that allows you to do something like this:
{{ 'cd' in 'abcde' }} {# returns true #}
You can't use preg_match() directly but there are ways to accomplish it:
if your list is an entity, add a method matches(): {{ (list.matches(b)) ? something : else }}
you could create a custom Twig extension function that uses preg_match() internally http://symfony.com/doc/master/cookbook/templating/twig_extension.html
Expanding from Serge's comment and is the correct answer.
In my example my string is "Message Taken - 12456756". I can then use |split to convert it into an array and use |replace to get ride of white space.
{% set mt = 'Message Taken' in d.note %}
{% if mt == true %}
{#.. you can then do something that is true#}
{% set mt_array = d.note|split('-') %}
{{ mt_array[0] }} | {{ mt_array[1]|replace({' ' : ''}) }}
{% endif %}
This would output my string but I now control two parts instead of 1.

Categories