I have a list of sortiments that contain shoe size and pair numbers, taken from a csv file with php and saved as an array in in Twig.
In twig this is my previous code to make a table. the problem here is, it is made to only make tables with 6 columns and not more or less.
<div class="twp-sortiment">
{% for key in page.extensions.TwpSortiment.data %}
{% set shoeSizeArray = key.shoesize|split(',') %}
{% set sortimentArray = key.sortiment|split(',') %}
{{ sortimentArray[2] }}
<table>
<tr>
<th>{{ shoeSizeArray[3] }}</th>
<th>{{ shoeSizeArray[4] }}</th>
<th>{{ shoeSizeArray[5] }}</th>
<th>{{ shoeSizeArray[6] }}</th>
<th>{{ shoeSizeArray[7] }}</th>
<th>{{ shoeSizeArray[8] }}</th>
</tr>
<tr>
<td>{{ sortimentArray[3] }}</td>
<td>{{ sortimentArray[4] }}</td>
<td>{{ sortimentArray[5] }}</td>
<td>{{ sortimentArray[6] }}</td>
<td>{{ sortimentArray[7] }}</td>
<td>{{ sortimentArray[8] }}</td>
</tr>
</table>
{% endfor %}
</div>
As you can see i have put my rows in to arrays (shoeSizeArray, shoeSizeArray).
Now i would like to create the table based on how many keys come after index 2, starting from index 3, my table should take values and increase until its at the end. so i tried this but obviously doesnt work as i lack knowladge about Twig.
<div class="twp-sortiment">
{% for key in page.extensions.TwpSortiment.data %}
{% set shoeSizeArray = key.shoesize|split(',') %}
{% set sshoeSizeArray = key.sortiment|split(',') %}
{{ sortimentArray[2] }}
<table>
<tr>
{% for key in shoeSizeArray %}
{% set counter = ( counter | default(2) ) + 1 %}
<th>{{ shoeSizeArray[counter] }}</th>
{% endfor %}
</tr>
<tr>
{% for key in sortimentArray %}
{% set counter = ( counter | default(2) ) + 1 %}
<td>{{ sortimentArray[counter] }}</td>
{% endfor %}
</tr>
</table>
{% endfor %}
</div>
This is the output:
As you can see I get 3 more emtpy table columns because im counting every key but I dont want the first 3 keys to be counted in my "for loop",now I have to say count the key of array - 3 (for till index 2: [0],[1],[2]) and then do the and for that amount of
Number of the keyCounter -3.
use slice with split filter https://twig.symfony.com/doc/3.x/filters/slice.html
like
{% set shoeSizeArray = key.shoesize|split(',')|slice(3) %}
{% set sortimentArray = key.sortiment|split(',')|slice(4) %}
Related
I am currently working with Python Flask and Bootstrap.
I am looking to get it so that if there are 4 cards in one row, it will automatically create a new row.
Issue i am having just now is the more posts I have the longer and thinner the rows cards get.
Current code:
{% extends "base.html" %}
{% block content %}
<div class="card-deck">
{# Go through each forum post #}
{% for post in forum_posts.items %}
<div class="card">
<div class="card-body">
<span class="badge badge-info">{{ post.cat }}</span>
<h3 class="card-title"><a class="card-title"
href="{{ url_for('forum_posts.view_post', forum_post_id=post.id) }}">{{ post.title }}</a>
</h3>
<h6 class="card-subtitle mb-2 text-muted">Written by: {{ post.author.username }}</h6>
<p>{{ post.text[:100] }}...</p>
</div>
<div class="card-footer">
<a href="{{ url_for('forum_posts.view_post', forum_post_id=post.id) }}"
class="btn btn-primary">Read
Blog Post</a>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
You could code this on the python side so that it makes it easier in jinja2, using an array of arrays:
>>> arr = [0,1,2,3,4,.....,102]
>>> forum_posts.items = []
>>> for i in range(int(len(arr)/4)):
j = i * 4
forum_posts.items.append([arr[j], arr[j+1], arr[j+2], arr[j+3]])
# needs an error trap for IndexError on 103
Then in jinja2: you can double loop:
{% for row in forum_posts.items %}
{% for item in row %}
{# HTML here for a new row of at most 4 cards #}
There is a way of doing the same kind of thing in jinja2 using variable loop counters and setting new row HTML if for example the new loop index is an exact multiple of 4:
{% for i, post in enumerate(forum_posts.items) %}
{% if i % 4 == 0 %}
{# new row code #}
{% else %}
{# regular row code %}
{% endif %}
{% endfor %}
I'm working on the index portion of the finance pset. I can't get the stock information to show up in the html table. I'm having a difficult time thinking how to loop through the stock information without having to create a new dictionary with the new data. Could someone help me with this direction that I'm taking? And can someone give me a "better" approach? I feel like this is not the "best" way to solve this problem. Hopefully the code appears correctly, I'm still learning how to use this site.
#app.route("/") #login_required def index():
"""Show portfolio of stocks"""
#set portfolio GROUPED BY symbol
portfolio = db.execute("SELECT symbol, SUM(shares) AS share_total FROM portfolio WHERE user_id = :user_id GROUP BY symbol", user_id = session["user_id"])
row = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id = session["user_id"])
remaining_cash = row[0]["cash"]
total_holding_value = 0
stock_info = {}
for stock in portfolio:
symbol = stock["symbol"]
shares = stock["share_total"]
quote = lookup(symbol)
price = quote["price"]
holding_value = shares * price
total_holding_value += holding_value
stock_info.update({"symbol":symbol, "shares":shares, "price":price, "holding_value":holding_value})
grand_total = total_holding_value + remaining_cash
return render_template("index.html", stock_info = stock_info, remaining_cash = remaining_cash, grand_total = grand_total)
{% extends "layout.html" %}
{% block title %}
Portfolio
{% endblock %}
{% block main %}
<table class="table table-bordered">
<thead>
<th>Symbol</th>
<th>Shares</th>
<th>Price</th>
<th>Total</th>
</thead>
<tbody>
{% for stock in stock_info %}
<tr>
<td>{{ stock.symbol }}</td>
<td>{{ stock.shares }}</td>
<td>{{ stock.price }}</td>
<td>{{ stock.holding_value }}</td>
</tr>
{% endfor %}
<tr>
<td></td>
<td></td>
<td>Remaining Balance:</td>
<td>{{ remaining_cash }}</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Grand Total:</td>
<td>{{ grand_total }}</td>
</tr>
</tbody>
</table>
{% endblock %}
One problem is here stock_info.update({"symbol":symbol, "shares":shares, "price":price, "holding_value":holding_value}). From the python doc [empashis added].
update([other])
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.
Chances are you want to send a list of dictionaries to the html. Consider declaring stock_info a list, and using the append method to add each stock.
I want to populate my table in twig with a for loop and some if statement.
{% for user in users %}
<td>
{% if user.planningday == 1 %}
{{user.name}} {{user.lastname}}
{% endif %}
</td>
<td>
{% if user.planningday == 2 %}
{{user.name}} {{user.lastname}}
{% endif %}
</td>
<td>
{% if user.planningday == 3 %}
{{user.name}} {{user.lastname}}
{% endif %}
</td>
<td>
{% if user.planningday == 4 %}
{{user.name}} {{user.lastname}}
{% endif %}
</td>
<td>
{% if user.planningday == 5 %}
{{user.name}} {{user.lastname}}
{% endif %}
</td>
{% endfor %}
But that's not working and i dont know why.
Example :
I try to populate my planning with 2 user. The first user select the day 5 so friday, the second user select the day 1 so monday. In my planning, first user have his name displaying on the friday , the second one is displaying after the friday and not on the monday . Thanks for your help.
The problem is you loop all the user, thus creating a calendar for all the users. If you want to group the users into one table try this aproach
{% for i in 1..5 %}
{% set assigned_user = '' %}
{% for user in users if user.planningday == i %}
{% set assigned_user = user %}
{% endfor %}
<td>{{user.name}} {{user.lastname}}</td>
{% endfor %}
twigfiddle
I have a twig template that uses batch() to make some columns like that:
{% set rows = collection|batch(3) %}
As documented here: http://twig.sensiolabs.org/doc/filters/batch.html this function takes a second argument to define the string that is used for "missing" elements.
I am looking for something like that:
{% set html = include 'path/to/file.html.twig' %} <-- parse error
{% set rows = collection|batch(3, html) %}
Is there a way to do that or something else I can/should do?
You can assign a chunk of text by using the following snippet:
main.twig
{% set foo %}
{% include 'foo.twig' %}
{% endset %}
{% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %}
<table>
{% for row in items|batch(3, foo) %}
<tr>
{% for column in row %}
<td>{{ column }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
foo.twig
<div>
<h1>Foo</h1>
</div>
twigfiddle
{{loop.index}} correctly dereferences the innermost loop. I'm not seeing a way to identify which loop index I'd like, however, if I have more than one loop nested.
http://jinja.pocoo.org/docs/dev/templates/
YES. This part of the documentation exactly answers my question!
The special loop variable always points to the innermost loop. If it’s
desired to have access to an outer loop it’s possible to alias it:
<table>
{% for row in table %}
<tr>
{% set rowloop = loop %}
{% for cell in row %}
<td id="cell-{{ rowloop.index }}-{{ loop.index }}">{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
http://jinja.pocoo.org/docs/dev/tricks/#accessing-the-parent-loop