I'm not quite sure if Jinja is the right tool for the job, but seeing as it's used elsewhere in our environment I thought I'd try and use this as an exercise to familiarise myself with it.
I have a list a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
I need to write the values in it to create a CSV file. All values in the CSV file will be fixed except for the values in a.
So I imagine a template file will look something like this (I know this is not Jinja2 syntax):
a[0], 'something',
a[1], 'else',
a[2], 'but',
.
.
a[5], 'repeated statement',
a[6], 'repeated statement',
.
a[8], 'here endeth the lesson',
Can I access the elements in 'a' by index like I would in Python and create my output file?
I'm not sure what exactly your end goal is, but jinja is more of a templating tool for generating views, rather than some kind of file. Like what #Marat said, you could use the csv module to create a csv file.
However, if your real purpose is to use jinja to create some type of table view where the values in your list are populated in the table, then you can certainly do that in jinja.
In your HTML view, you would do something like this:
<table>
<thead>
<tr>
<th>List[idx]</th>
<th>Value</th>
</tr>
<thead>
<tbody>
{%- for item in a -%}
<tr>
<td>a[{{ loop.index - 1 }}]</td>
<td>{{ item }}</td>
</tr>
{%- endfor -%}
</tbody>
</table>
Of course, you have to pass your a list as a context variable to your jinja in order for this to work. I'm assuming you're using Flask as your framework:
#app.route('/your-route')
def your_route_function():
... # your code for creating the 'a' list
... # more code
return render_template('yourhtml.html', a=a)
Now, if you want to access your list by index, that's possible too. You would have to determine the length of your list though using jinja's length filter:
<table>
<thead>
<tr>
<th>List[idx]</th>
<th>Value</th>
</tr>
<thead>
<tbody>
{%- for idx in range(a|length) -%}
<tr>
<td>a[{{ idx }}]</td>
<td>{{ a[idx] }}</td>
</tr>
{%- endfor -%}
</tbody>
</table>
Related
I am following this video and everything is working perfectly. The output of a SQL query is saved within a variable that I can call on in another .html page.
so my sql query is:
#app.route('/all_data')
def all_data():
customers = db.get_customers()
for customer in customers:
var = customers
return render_template('all_data.html',var=var)
When calling this {{var}} in all_data.html page the output is for a long tuple:
('name','email','comment','gender'),('name','email','comment','gender') etc etc
I am looking to put this {{var}} into a table instead?.. I but am hitting a brick wall in finding out how to do this?
any help would be much appreciated!
Assuming you're using Flask's default template engine (Jinja2), you can simple use a for loop to iterate over the elements of the collection inside the template. The syntax is:
{% for item in items %}
{{ item }}
{% endfor %}
So simply create an HTML table, and add a row for each item in your var variable.
IIRC, Jinja tuples act the same as Python's, so you can probably do something along the lines of:
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Comment</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
{% for current in var %}
<tr>
<td>{{ current[0] }}</td>
<td>{{ current[1] }}</td>
<td>{{ current[2] }}</td>
<td>{{ current[3] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
I haven't checked it (as I don't have a Flask project available right now), but if my memory serves me right, that's how I would do it
Here's a link to an usefull part of Jinja2's documentation
Also, what is this piece of code for ?
for customer in customers:
var = customers
You're iterating over each element of the list, but your never use the customer variable (containing the current element). Instead, you assign the var variable to the customers list multiple times. Assuming customers is a simple Python list, you could remove this loop and simply do return render_template('all_data.html',var=customers)
Say I have a list of lists like:
table = [[1,2,3],[4,5,6],[7,8,9]]
which can be have a dynamic number of lists and I want to render it into my web page like so:
#app.route("/")
def home():
return render_template('home.html', tbl=zip(*table))
I want to write in my home.html file so that it can write the table. Originally, my web page had:
{% for col1, col2 in tbl %}
<tr>
<td>{{ col1 }}</td>
<td>{{ col2 }}</td>
</r>
{% endfor %}
where col1 and col2 were arguments originally passed into tbl
tbl=zip(col1, col2)
but I'm not sure how to write the html code so that it can read a dynamic number of columns.
You do not need to use unpacking when rendering your table as simple iteration will suffice:
<table>
{%for row in tbl%}
<tr>
{%for col in row%}
<td>{{col}}</td>
{%endfor%}
</tr>
{%endfor%}
</table>
I have a SQL query in a Django view and store the results in a variable. As far I know the result should be stored as a list.
def assignments(request):
cursor = connection.cursor()
cursor.execute("SELECT o.article_id, o.amount, m.id, o.create_date, m.status FROM orders o, producers p, machines ma, matches m WHERE ma.producer_id=1 AND m.machine_id = ma.id AND m.order_id = o.id")
articles = cursor.fetchall()
context = {"article_list": articles}
return render(request, 'assignments.html', context)
Then I want to transfer that data row by row in a table in my template.
{% block body %}
<div class="container">
<table class="table">
<thead>...</thead>
<tbody>
{% for articles in article_list %}
<tr>
<td>{{ articles.article_id }}</td>
<td>{{ articles.amount }}</td>
<td>{{ articles.id}}</td>
<td>{{ articles.create_date }}</td>
<td>{{ articles.status }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
Unfortunately the table is empty and is not showing any results.
The query itself should be fine. I tested the query in my database workbench and it is showing the correct results.
How can I access the data stored in variable articles from my template?
PS: I'm far from being a programmer. So I don't really know any programming concepts/language.
Any help is highly appreciated. Thanks!
You have a list of lists. Each element in articles_list is just a list of values from the database; it does not have any knowledge of attributes like "id" or "amount".
As Arpit says in the comments, you should be using Django models for this rather than raw SQL.
I have recently tried to solve the challenge of handling a dynamic number of columns in my Django template (essentially working through a list containing lists that isnt standerdized).
I pass two things to my view:
test_array: an array that looks something like the following [[1,2,3],[1,2,3],[1,2,3]]
numbers: in this case 3 (indicating the number of attributes in the sub lists
I thought to solve this as follows:
<tbody>
{% for t in test_array %}
<tr>
{% for x in numbers %}
<td>{{ t.x }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
But the above returns no output. When I reference t.1, t.2 etc hardcoded this returns output.
As such, what is the best way to handle a dynamic number of columns in Django? Or, is there a more elegant way to solve the above?
Passing the length of the sublists to the the template isn't necessary.
As the list elements are also lists the inner loop could simply be reduced to this:
{% for x in t %}
<td>{{ x }}</td>
{% endfor %}
Hello I am using jinja2 and I have a list of dictionaries that I am passing to jinja template.
{%for dict in list_of_dicts%}
<tr>
{%for key in my_dict.keys()%}
<td> {{my_dict.key}}</td> // Here i want to get value in my_dict with that particular key.
{%endfor%}
</tr>
{%endfor %}
How do I achieve this?
By using just one variable in your for-loop, you just get the value and not the key name. You can use the alternative key, value syntax (as documented here) in a for loop to get the keys in a separate variable, like this:
{% for key, value in my_dict.iteritems() %}
<td>{{ key }}</td>
{% endfor %}