Symfony twig use keys in for loops - twig

Does somebody know an other way to do that with twig, because it returns me an error :/
{% for key, conversation in conversations %}
{% set lastMessage = sortedConversations.key %}
<p>{{ lastMessage }}</p>
{% endfor %}
Here is the error returned :
Key "key" for array with keys "0" does not exist
Thanks !

I'm not sure to understand, but may be you can try this:
sortedConversations[key]
instead of
sortedConversations.key

Try this:
{% for key, conversation in conversations %}
{% set lastMessage = sortedConversations[key] %}
<p>{{ lastMessage }}</p>
{% endfor %}
Note the brackets around key.
This way, twig should notice key as a variable and not as a simple string.

Related

Twig check elements of array are in another array

I'm trying to check in twig if any element of one array are set in other array.
Example:
I have user.roles with ['ROLE_ADMIN','ROLE_MANAGER'] and I have the product.roles with ['ROLE_ADMIN','ROLE_USER'].
I want to check (in Twig) if any user.roles are in product.roles, like:
{{ user.roles[0] is product.roles|keys }}
But with each element of user.roles in the same function.
Does anyone know how?
You could use the filter filter to do this, but guessing it would be better to move this to PHP / TwigExtension
{% if user.roles |filter((role) => role in product.roles) | length > 0 %}
Can do something with the post
{% else %}
Access denied
{% endif %}
demo
Use a for loop:
{% for role in user.roles %}
{% if role in product.roles|keys %}
do something...
{% endif %}
{% endfor %}

How can I iterate over the terms in a taxonomy outside the list.html using Zola?

I've found out you can use
{% set posts = get_taxonomy(kind="posts") %}
to retrieve a taxonomy but I'm clueless how to iterate over the terms of the taxonomy in for example single.html of this taxonomy.
I tried things like the following, but I get:
"Tried to iterate using key value on variable 'posts', but it is
missing a key"
{% set posts = get_taxonomy(kind="posts") %}
{% for term in posts %}
<li class="list__item">
<a href="{{ term.permalink }}">
{{ term.name }}
</a>
</li>
{% endfor %}
get_taxonomy returns a struct with keys items & kind. You can debug using:
{% set posts = get_taxonomy(kind="posts") %}
<code>{{ posts.kind | json_encode(pretty=true) }}
{{ posts.items | json_encode(pretty=true) }}</code>
kind seems to have TaxonomyConfig structure and each element in items seems to have TaxonomyTerm structure.

Symfony & Twig: how to get vars in twig by DB data?

One question please.
{{ dump(app.user.slugName) }}
If I do the above snippet in Twig, I get the slugName of the user loged ("my-user-2", i.e.) in the app (SlugName is an atribute of the entity user). Ok & Correct. But... I want to order this action from a var (var from BD data)
I have a variable named option which is set like this:
{% set option = 'app.user.slugName' %}
But when I'm trying output this variable with {{ dump(option)}} it returns app.user.slugName as literal. It does not return my-user-2.
Is there are any way in twig to solve this? It's a function to generate a menu, but some links needs some parameters.
I see what you mean, but Twig can't evaluate expression like that.
To achieve something like that you would need a snippet like this,
{% set value_methods = 'app.user.slugname' %}
{% set option_value = _context %}
{% for method in (value_methods|split('.')) if method != '' %}
{% set option_value = attribute(option_value, (method|replace({'()': '', }))) %}
{% endfor %}
{{ option_value }}
twigfiddle
(edit)
Remember you can create a macro to achieve some reusability for this snippet,
{% import _self as macros %}
{{ macros.evaluate(_context, 'app.user.slugname') }}
{% macro evaluate(context, value_methods) %}
{% set option_value = context %}
{% for method in (value_methods|split('.')) if method != '' %}
{% set option_value = attribute(option_value, (method|replace({'()': '', }))) %}
{% endfor %}
{{ option_value }}
{% endmacro %}

loop through key values of an array in twig

I have not been able to find my answer elsewhere (maybe because I didn't know how to ask google as I'm pretty new to this ;))
I'm working with symfony and twig.
I pass an array in my view with only one entry related to the id. It looks like this in my view
array:2 [▼
"sponsor" => Sponsor {#473 ▼
-id: 5
-sponsorCode: "FUT"
-name: "MANULO"
-city: "OLERDOLA"
-zipCode: 0
-address: ""
-country: "ESPANA"
-phoneNumber: 32767
-email: ""
-creationDate: DateTime {#470 ▶}
}
"app" => AppVariable {#476 ▶}
]
I know I can access each property by doing
{{sponsor.name}}
But I'm trying to do it through a loop for each field of this array
something like
{% for key, value in sponsor %}
<div class="field-group">
<div class="field">{{ key }}:</div>
<div class="value">{{ value }}</div>
</div>
{% endfor %}
Am I missing something?
Thank you very much
From the TWIG documentation:
Keys Only
By default, a loop iterates over the values of the sequence. You can iterate on keys by using the keys filter:
<h1>Members</h1>
<ul>
{% for key in users|keys %}
<li>{{ key }}</li>
{% endfor %}
</ul>
Keys and Values
You can also access both keys and values:
<h1>Members</h1> <ul>
{% for key, user in users %}
<li>{{ key }}: {{ user.username|e }}</li>
{% endfor %} </ul>
https://twig.sensiolabs.org/doc/2.x/tags/for.html
Keep your eye on the TWIG documentation, its rather comprehensive.
Looking at your code, it looks ok. However, the issue could be that the {{value}} may need further identification, such as {{ value.id }}

Twig get object names ending with numbers dynamically

I have some objects like address1, address2, address3 ... address10. All these objects have lat and long values.
I know we can get it from the attribute() function of Twig, but what I want in my twig template is to get the main objects
{% for i in 1..10 %}
{% set address = address~i %}
{{ address.lat }}
// or like
{{ attribute(address, 'lat') }}
{% endfor %}
Just simply use :
{% for i in 1..10 %}
{{ attribute(attribute(_context, 'address'~i), 'lat') }}
{% endfor %}

Resources