I am to DRY in a twig template. I am wondering is you can access a variable in the {{ notation }} of twig.
For example:
{% if page.lang == 'en' %}
// do something
{{ content_en }}
{% endif %}
{% if page.lang == 'es' %}
// hacer algo
{{ content_es }}
{% endif %}
I tried some other approaches. But is it possible to (somehow) combine variables and do something like this:
// Php example
$var = 'content_';
$var .= page.lang;
// Output would be 'content_en';
But then for Twig?
// Something like
{{ content_ + page.lang }}
To make it more clear. I would like to access to correct variable.
$content_en = 'this is just some content';
$content_es ='Alguna informaciĆ³n';
$var = 'content_';
$var .= 'en';
$key = ${$var};
// Output is 'this is just some content'
echo $key;
If you want to concatenate the output you need to use ~
{{ 'content_' ~ page.lang }}
If you want to call a dynamic variable you need to use attribute
{{ attribute(_context, 'content_' ~ page.lang) }}
_context is a special variable in twig which containts all variables you passed towards the template
#Darabee.
You are correct, the syntax would be:
{{ attribute(_context, 'content_' ~ page.lang) }}
But how ever I noticed that if there is a array and u use '.' instead of a underscore '_' it will not work.
In my case I have a multi-array. That is the issue.
page['city']['content_en'].
or page.city.content_en
Related
I have a problem with properties in (probably) Twig. I have controller in Symfony where getCategories(), getWords(), getTranslations() methods (from Doctrine) return the objects (relations). Every property in the controller is an array because I call findAll() method (from Doctrine again) which returns the array. Finally I return all the properties from controller to view (Twig file) where I try display the results by Twig for loop.
The problem is the Twig loop only iterates over flashcards property (I know why ;)) and I have no idea how to make many-properties iterating. I'd like the loop to iterate over all properties returned by the controller.
In the controller foreach loop I tried update the flashcards array with new associative keys such as: category, word and translation so that all the results returned by Doctrine (including relations) are stored in one flashcards property but then Symfony throws exceptions.
I wondered if create one array in the controller to which I would push the flashcards, cateogry, word and translation arrays and then return this one array to the view but I don't think this is good practice.
Here's the controller method code:
public function showAllCards()
{
$flashcards = $this->getDoctrine()->getRepository(Flashcards::class)
->findAll();
foreach ($flashcards as $flashcard) {
$category = $flashcard->getCategories()->getName();
$word = $flashcard->getWords()->getWord();
$translation = $flashcard->getTranslations()->getWord();
}
return $this->render('try_me/index.html.twig', [
'flashcards' => $flashcards,
'category' => $category,
'word' => $word,
'translation' => $translation
]);
}
Here's the Twig loop code:
{% for flashcard in flashcards %}
{{ word }}
<br>
{{ flashcard.pronunciation }}
<br>
{{ flashcard.exampleSentence }}
<br>
{{ category }}
<br>
{{ translation }}
<br>
{% endfor %}
I tried to execute the following controller code...
public function showMeAll()
{
$flashcards = $this->getDoctrine()->getRepository(Flashcards::class)
->findAll();
foreach ($flashcards as $flashcard) {
$flashcards['categories'] = $flashcard->getCategories()->getName();
$flashcards['words'] = $flashcard->getWords()->getWord();
$flashcards['translations'] = $flashcard->getTranslations()->getWord();
}
return $this->render('try_me/index.html.twig', [
'flashcards' => $flashcards,
]);
}
...with the following Twig loop...
{% for flashcard in flashcards %}
{{ flashcard.words }}
<br>
{{ flashcard.pronunciation }}
<br>
{{ flashcard.exampleSentence }}
<br>
{{ flashcard.categories }}
<br>
{{ flashcard.translations }}
<br>
{% endfor %}
...but then Symfony says:
An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Proxies__CG__\App\Entity\Words could not be converted to string").
Could you give me some tips how to solve this problem, please? I'd like the Twig loop to iterates over many properties (flashcard, word, category, translation). Or write if there's a better solution, please.
Thank you in advance for every answer!
According to your snippets, I'm guessing you want something like the following:
{% for flashcard in flashcards %}
{% for word in flashcard.getWords() %}
{{ word }}<br />
{% endfor %}
{{ flashcard.getPronunciation() }}<br>
{{ flashcard.getExampleSentence() }}<br>
{% for category in flashcard.getCategories()() %}
{{ category.getName() }}<br />
{% endfor %}
{% for translation in flashcard.getTranslations() %}
{{ translation.getWord() }}<br />
{% endfor %}
{% endfor %}
Have a look at this section of the documentation. Basically if you had foo.bar, twig will test if bar is a public property of foo and if not test if there is a public getter, getBar, to fetch bar.
Some sidenotes in both of your loops, the values category, word and translation will only hold the last value of your flashcards, because you are overwriting the value each time.
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') %}
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}"] }}
How to call a variable's method in expression syntax in twig tempting system.
see the example below
{{ myObj.someMethod() }} {# this print the output of this method #}
i don't want above code because its printing output of this method.
but i want this
{% myObj.someMethod() %}
but its is giving me error that
Unknown tag name "myObj" in "
{% myObj.someMethod() %}" at line 2
even with above error method is also being called.
In twig syntax {{ some variable}} will print the result in variable you need to set variable and then use where you want
{% set myvar = myObj.someMethod() %} /* this will store the result returned from function */
{{ myvar }} /* this will print the result in myvar */
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.