Nested for do not accept a variable - twig

I've got a problem with display of this function:
{% for row in topics %}
<tr align="center">
<td class="td"><img src="{{ asset('images/tdlogo.jpg') }}" alt="Logo"></td>
<td align="left" class="td"><a href="{{ url('topic_view', {'slug': row.idForumSection, 'id': row.idForumTopic}) }}"
title="{{ row.nameTopic }}">{{ row.nameTopic }}</td>
{% for row in posts %}
<td class="td">{{ row.post }}</td>
{% endfor %}
</tr>
{% endfor %}
There is a for which creates table showing forum topics, and a second for inside which is supposed to display post count for each topic. However, as it is two fors inside each other, second one iterates fully before next topic is displayed. As an affect, every topic shows all counts of topic posts from each topic.
Meanwhile, first topic should have posts:4, and second posts:1.
I tried to do something like this:
<td class="td">{{ posts.0.post }}</td>
And it works, but show first topic number of posts for all of topics.
Replacing "0" with a variable which would increase with each iteration of first "for" would work (so starting with 0, then 1, then 2, displaying numbers of posts for each topic), but i cannot make variable work inside this function.
Here is a dump of functions calling to database for variables (there are two functions, one for topics and second one for posts).
array(2) { [0]=> array(3) { ["nameTopic"]=> string(9) "Regulamin" ["idForumSection"]=> string(1) "1" ["idForumTopic"]=> string(1) "1" } [1]=> array(3) { ["nameTopic"]=> string(13) "Administracja" ["idForumSection"]=> string(1) "1" ["idForumTopic"]=> string(1) "5" } }
topics:
array(2) { [0]=> array(3) { ["nameTopic"]=> string(9) "Regulamin" ["idForumSection"]=> string(1) "1" ["idForumTopic"]=> string(1) "1" } [1]=> array(3) { ["nameTopic"]=> string(13) "Administracja" ["idForumSection"]=> string(1) "1" ["idForumTopic"]=> string(1) "5" } }
posts:
array(2) { [0]=> array(3) { ["idForumTopic"]=> string(1) "1" ["idForumSection"]=> string(1) "1" ["post"]=> string(1) "4" } [1]=> array(3) { ["idForumTopic"]=> string(1) "5" ["idForumSection"]=> string(1) "1" ["post"]=> string(1) "1" } }
Please, help me!

Related

Fixed array name to Dynamic

I would like to change a fixed array name to a dynamic array name.
Within a
set item_classes = [
item.original_link.nid and item.original_link.p6 and item.original_link.in_active_trail ? 'active',
]
This works because the 'nid' and p6 are the same and unique.
Within the item.original_link array there are 19 values:
'nid' => string(3) "114" - Node ID
'bid' => string(3) "100"
'pid' => string(3) "111"
'has_children' => string(1) "0"
'weight' => string(1) "0"
'depth' => string(1) "3" - Page Depth
'p1' => string(3) "100"
'p2' => string(3) "111"
'p3' => string(3) "114" - P+Depth
'p4' => string(1) "0"
'p5' => string(1) "0"
'p6' => string(1) "0"
'p7' => string(1) "0"
'p8' => string(1) "0"
'p9' => string(1) "0"
'in_active_trail' => boolTRUE
'access' => boolTRUE
'title' => string(21) "Development.twig.html"
'options' => array(0)
I need to set the value of the item.original_link.p6 to a dynamic value of: 'p + depth'.
As in this example, the value would be item.original_link.p3.
I hope I have explained this in enough detail for someone to help or give me direction.
I have added a set variable as below:
{% set my_var = [ ('p' ~ item.original_link.depth ), ] %}
This gives me the desired dynamic variable, but when I use this in the next set as below:
{% set item_classes = [ item.original_link.nid and item.original_link.my_var and item.original_link.in_active_trail ? 'is_active', ] %}
it returns NULL

how to sort a dictionary by the value of a key in the dictionary?

I wrote my own wishlist in python3 flask (with apache mod_wsgi)
this is my data structure for the wishlist items:
{
},
"": {
"images": {
"pic": ""
},
"buylinks": {
"": {
"link": "",
"price": ""
}
},
"want": "",
"comments": ""
}
}
for example:
"Nintendo Joy-Con (L/R) - Gray": {
"images": {
"pic": "wishlist/joycons-grey.jpg"
},
"buylinks": {
"Amazon": {
"link": "https://www.amazon.com/dp/B01N6QKT7H",
"price": "66.99"
}
},
"want": "7/10",
"comments": "extra joycons for playing with friends on my switch"
},
right now every time I update the json file containing the wishlist data the apache server jinja template spits it iut in a different order
my jinja template looks like
<table>
<tr>
<th>Name</th>
<th>Image(s)</th>
<th>Links To Buy</th>
<th>Want/10</th>
<th>Comments</th>
</tr>
{% for key in wishlist.keys() %}
<tr>
<td><b>{{ key }}</b></td>
<td>{% for image in wishlist[key]["images"].keys() %}
<img src="{{ url_for('static', filename=wishlist[key]["images"][image]) }}" width="250px">
{% endfor %}</td>
<td>{% for merchant in wishlist[key]["buylinks"].keys() %}
{{ merchant}} (~${{ wishlist[key]["buylinks"][merchant]["price"] }})
<br>{% endfor %}</td>
<td><a> {{ wishlist[key]["want"] }} </a></td>
<td> {{ wishlist[key]["comments"] }}</td>
</tr>
{% endfor %}
</table>
how do I modify the {% for key in wishlist.keys() %} line to sort the wishlist by the value of the want key such that 10/10 is at the beginning and 0/10 is at the end? (the value to use to sort the example item would be "7/10")
I think I need to use the "sorted" function but I'm not sure how to
so to get this to work I had to add
wishlist_keys = sorted(wishlist.keys(), reverse=True, key=lambda x: wishlist[x]["want"] )
to my flask python code and pass wishlist_keys into render_template()
and change the template to
{% for key in wishlist_keys %}

ordering an array of object with twig

I need to order a list of objects i receive with an inner property.
I receive a list of objects like that :
{ match: "italy - germany", date: "27/01/2019", competion: "World cup" }
{ match: "lille - paris", date: "23/01/2019", competion: "coupe de france" }
{ match: "om - psg", date: "13/01/2019", competion: "coupe de france" }
{ match: "russia - poland", date: "25/01/2019", competion: "World cup" }
I don't know where to start but i need to loop over matches:
{% for match in matches %}
I want to obtain this list:
coupe de france :
om - psg
lille -paris
world cup :
italy germany
russia - poland
{% set data = [
{
'country' : 'france',
'match': 'G',
},
{
'country' : 'belgium',
'match': 'F',
},
{
'country' : 'france',
'match': 'E',
},
{
'country' : 'germany',
'match': 'D',
},
{
'country' : 'germany',
'match': 'C',
},
{
'country' : 'france',
'match': 'B',
},
{
'country' : 'italy',
'match': 'A',
},
] %}
{% set sorted = [] %}
{% for row in data %}
{% if not ((row.country) in sorted|keys) %}{% set sorted = sorted|merge({ (row.country) : [], }) %}{% endif %}
{% set sorted = sorted|merge({(row.country): (sorted[(row.country)]|merge([ row.match, ])|sort)}) %}
{% endfor %}
{% for country, values in sorted %}
{{ country }}
{% for value in values %}
- {{ value }}
{% endfor %}
----------------------------
{% endfor %}
demo
You can try snilius/twig-sort-by-field.
With this Twig extension, you can do somthing like this:
{% for match in matchs|sortbyfield('competion', 'desc') %}
{{ dump(match) }}
{% endfor %}

print variable's value contain variable is it possible in twig? like php we have used $$ to print variable value?

i have user object that contain all user fields.
and listFields array that have ["user.id", "user.email","user.gender"].
so variables in string.
i want to loop listFields and print it's original value from user object
currently user.id user.email print on screen.
i want to print it's value in screen.
have any solution for this! or it is possible?
Mycode
{% for fieldName in listFields %}
<td>
{{ fieldName }}
</td>
{% endfor %}
If you want to print dynamic variables u can make use of the function attribute:
{% set user_fields = [ 'user.id', 'user.email', 'user.gender', 'alice.email', 'bob.id', 'bob.foo', ] %}
{% for field in user_fields %}
{{ attribute(attribute(_context, (field|split('.'))[0])|default([]), (field|split('.'))[1])|default(null) }}
{% endfor %}
demo
array:3 [▼
"user" => array:3 [▼
"id" => 42
"email" => "user#example.com"
"gender" => 0
]
"bob" => array:3 [▼
"id" => 1
"email" => "bob#example.com"
"gender" => 0
]
"alice" => array:3 [▼
"id" => 100
"email" => "alice#example.com"
"gender" => 1
]
]

how does foreach works in react-redux

I am making a nodejs app which can fetch flights from the KIWI api, it returns a json list, and since you parameters like from and to, it should return a list of flights.
I can successfully get that, but when I want to display everything I dont know how to do it.
This is my render:
render(){
return (
<table className="table table-hover">
<thead>
<tr>
<th>Flight #</th>
<th>From</th>
<th>To</th>
</tr>
</thead>
<tbody>
{this.props.flights.map(this.renderFlights)}
</tbody>
</table>
);
}
and
renderFlights(flightData){
// add key to make them unique
return(
<tr>
<td>{flightData.data[0].id}</td>
<td>{flightData.data[0].mapIdfrom}</td>
<td>{flightData.data[0].mapIdto}</td>
</tr>
);
}
{this.props.flights.map(this.renderFlights)} just maps the first one in the array, I know that I have to use foreach, but I dont know how I can use this to print everything in the list, flight id plus the from and to, so when u fetch the flights u get around 15, and I want to be able to display all the 15 flights can someone help me out here?
this returns undefined for forEach:
<tbody>
{
this.props.flights.array.forEach(element => {
this.renderFlights
})
}
</tbody>
I found your API and test interface here: https://skypickerbookingapi1.docs.apiary.io/#reference/check-flights/checkflights/check_flights?console=1
So it seems that you are getting this object for your response:
{
"server_time": 1516568910,
"flights_checked": false,
"extra_fee": 0,
// blah blah,
"flights": [
// first flight
{
"bags_recheck_required": false,
"dtime_unix": 1524646800,
"extra": "",
"atime_unix": 1524651600,
"priority_boarding": {
"currency": null,
"price": null,
"is_possible": false
},
"price": 313,
"currency": "NOK",
"price_new": 313,
// blah blah
},
// second flight
{
"bags_recheck_required": true,
"dtime_unix": 1524683400,
"extra": "",
"atime_unix": 1524691800,
"priority_boarding": {
"currency": null,
"price": null,
"is_possible": false
},
"price": 1560,
"currency": "NOK",
"price_new": 1560,
// blah blah
},
// more and more flights
So I'm guessing that your "this.props.flights" is referring to the "flights" property of the above object.
Now, you need to use "map", not "foreach":
this.props.flights.map(this.renderFlights) //this is correct
And your callback function should be:
renderFlights(one_single_flight){
// add key to make them unique
return(
<tr>
<td>{one_single_flight.id}</td>
<td>{one_single_flight.src_country}</td>
<td>{one_single_flight.dst_country}</td>
</tr>
);
}
}
This is how I was able to get the result I wanted:
renderFlights(flightData){
const result = flightData._results;
var rows = [];
for (var i = 0; i < result; i++) {
rows.push(
<tr key={i} >
<td>{flightData.data[i].mapIdfrom}</td>,
<td>{flightData.data[i].mapIdto}</td>,
</tr>
);
}
return <tbody>{rows}</tbody>;
}
This prints all the available flights for some certain date.

Resources