loop through key values of an array in twig - 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 }}

Related

Iterating over ArrayEntity

We were have this backend code:
$event->getPage()->addExtension('downloads', new ArrayEntity($downloads));
In the twig
{{ dump(page.extensions.downloads) }}
shows the Array entity.
Before the Shopware updates
This loop worked:
{% for key, files in page.extensions.downloads.data %}
But now it doesn't (data is null)
Also
{% for key, files in page.extensions.downloads %}
does not work.
How to iterate over the array entity in twig?
{% for key, files in page.extensions.downloads.all %}
works

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.

Dynamic nav-bar elements - passed from Flask to Jinja - inherited layout template

Environment: Python 3.6, Flask 1.02, Jinja2
Objective:
Create a dynamic menu in layout.html (which is extended by content.html)
yet the url_for of the dynamic element is frequently requires a parameter to be passed
Issue statement:
How can I pass the parameters for url_for in Jinja template when rendering the template?
I feel like I would need the syntax of str().format in Jinja..
I tried to:
1. pass each part as a separate value:
menus = [{'url': 'func_name', 'menu_title': 'title', 'param': 'param_name', 'param_val': 'param_value'}]
return render_template('content1.html', menus=menus]
in jinja I tried to call it like: (I also tried it without the plus and double-quotes)
{{ url_for(func_name), param_name+ "=" + param_val }}
During rendering it gives error of
url_for() takes 1 positional argument but 2 were given
2. tried to use the {% set var_name: passed_variable %}
Built on 1st version of menus defined on server side, I tried to set the variables within Jinja, but also failed.
menus = [{'url': 'func_name', 'menu_title': 'title', 'param': 'param_name', 'param_val': 'param_value'}]
return render_template('content1.html', menus=menus]
Jinja
{% for menu in menus %}
{% set url = menu.get('url') %}
{% set param = menu.get('param') %}
{% set value = menu.get('param_val') %}
{% url_for(url, param + "=" + value %}
Yet it also didn't work.
It feels like if I give a param for the url_for syntax (not a hard-wired string) I cannot add the parameters.
3. tried to pass whole content of url_for as a string:
menus={'url_string': " 'func_name', param_name=param_value"}
yet it fails again as url_for syntacs put the whole between apostrophes, which I wouldn't need at the end.
Some references I scanned through.
Flask context-processor
It could work if I would create another template of each nav-bar for each content page - yet with that move i could simply move the navbar into the content page. However that seems dull. Stack Overflow topic
Thus question:
How can I pass the
param_id=paramval['id']
for the url_for syntax during rendering
{{ url_for('edit_question', param_id=paramval['id']) }}
The code/structure stg like below:
layout.html
<html>
<body>
{% for menu in menus %}
{% for key, value in menu.items() %}
<a href="{{ url_for(value) }}" >
{{ key }}
</a>
{% endfor %}
{% endfor %}
{% block content %}
{% endblock %}
</body>
</html>
content1.html
{% extends 'layout.html' %}
{% block content %}
content
{% endblock %}
content2.html
{% extends 'layout.html' %}
{% block content %}
content
{% endblock %}
app.py
#app.route('/')
def index():
menus = [{'menu_title1': 'menu_func_name1'}]
return render_template('content1.html', menus=menus)
#app.route('/menu_details/<int:menu_nr>')
def show_details_of_menu(menu_nr):
menus = [{'menu_title3': 'menu_func_name3', 'menu_param_name': 'menu_param_value'}
return render_template('content2.html', menus=menus)
sorry for the Wall of text..
sigh.. after hours I just found how to construct the syntax. I hope it will help others!
During rendering:
menus = [{'url': 'func_name', 'menu_title': 'title', 'parameters': {'param1': param1_value}}]
return render_template('context.html', menus=menus]
In Jinja, I adjusted the syntax to manage cases where no parameters are needed:
{% for menu in menus %}
{% if menu.get('parameters').items()|length > 0 %}
<a href="{{ url_for(menu.get('url'), **menu.get('parameters')) }}">
{{ menu.get('menu_title') }}
</a>
{% else %}
<a href="{{ url_for(menu.get('url')) }}">
{{ menu.get('menu_title') }}
</a>
{% endif %}
{% endfor %}

Symfony twig use keys in for loops

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.

Resources