Use suffix for twig - php

I have two twig array like arrayA,arrayB
arrayA = {1,2,3,4}
arrayB = {10,20,30,40}
each elements of arrayA is correspondent to arrayB.
then
{% for a in arrayA %}
{{ a }}
{{ arrayB[]}} <- I want to show the element of arrayB in order here
{% endfor %}
It's not difficult question for php.
you can use for (i=0;i < count(arrayA);i++){ arrayB[i]..
However I am not sure how to do this in twig.

You can achieve this with the loop variable:
{{ arrayB[loop.index0] }}

Related

How to iterate over many properties in Twig loop?

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.

How to get a value of a key in a twig array outside of a loop

I have an array of states and a number like:
(state, count)
states=[
'ACT' => 25,
'NSW' => 45,
'VIC' => 18,
'SA' => 12
]
I'm trying to get the value for each state in twig (outside of a loop).
So for each state (as a dynamic parameter) I need to get the "count" value:
{{ attribute(states, state_name).count }}
or
{{ attribute(states, count)}}
but not working.
Any idea?
Edit:
This code is working but can't get the value out of the loop.
In this code I need to run the loop several times.
{% for state in states %}
{% if state.state_name == state_name %}
({{ state.count }})
{% endif %}
{% endfor %}
There is no variable named count, you only have a key-value array where the value is the count. You can simply use attribute to get the value:
{{ attribute(states, state_name) }}
or, as jeroen commented:
{{ states[state_name] }}

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}}

Setting the result of a function to a variable in twig

I have a function that generates an array containing menu items:
Item 1
SubItem 1a
SubItem 1b
Item2
SubItem 2a
...
I have a twig extension that can return this as an array. I need to be able to set this array to a variable in twig, so that I can use it through out my template.
I have tried doing {% set myArray = {{ myFunction('menuname') }} %}
I also tried:
{% set myArray %}
{{ myFunction('menuname') }}
{% endset %}
However, that did not work either. Is there a way to do this?
Got it!
Use {% set myArray = myFunction('menuname') %}

Reference array from key in for loop with Twig

In Twig I am trying to iterate over a potentially incomplete array using a fixed-length for loop so I can show what values are empty.
In PHP this would be simplified to:
for($i =0; $i <= $limit; $i++) {
if($data[$i]) {
echo $data[$i];
}
)
The only thing is that in Twig I am having problems using the key (index) of the loop to reference a value in an array, this is what I've tried and expected to work, but doesn't:
{% for i in range(0, limit-1) %}
{{ data.i }}
{% endfor %}
I could obviously use array_pad() to pad out my array in my controller, but surely there must be a way to do this in twig?
How about this:
{% for i in range(0, limit-1) %}
{% if data[i] is defined %}
{{ data[i] }}
{% endif %}
{% endfor %}

Categories