Reputation: 87
I want to display the arrays elements in the given board. But I'm not able to do so.
This is my views.py:
from django.shortcuts import render
from django.http import HttpResponse
import numpy as np
import random
from time import sleep
#the home will accept request when the client will send it
def play(request):
#for request a response is created
#in HTTP format(changed)
return render(request,'play.html',{'name':'M'})
# Creates an empty board
def create_board(request):
arr=np.array([[0, 0, 0], [0, 0, 0],
[0, 0, 0]])
return render(request,'play.html',{'array':arr})
Below is the HTML code:
<table>
<tr>
<td></td>
<td class="vert"></td>
<td></td>
</tr>
<tr>
<td class="hori">{{array}}</td>
<td class="vert hori"></td>
<td class="hori"></td>
</tr>
<tr>
<td></td>
<td class="vert"></td>
<td></td>
</tr>
</table>
Below is the webpage's table where I wish to display array elements:
EDIT 1: This is how I tried to create a table:
<table>
{% for row in array %}
<tr>
{% if forloop.first or forloop.parentloop.first%}
<td class="hori"></td>
{% else %}
<td></td>
{% endif %}
{% for col in row %}
{% if forloop.first or forloop.parentloop.first %}
<td class="vert"></td>
{% else %}
<td></td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</table>
Upvotes: 1
Views: 1280
Reputation: 1108
I think what you exactly want can be achieved by doing something like this:
<table>
<tr>
<td>{{ array.0.0 }}</td>
<td class="vert">{{ array.0.1 }}</td>
<td>{{ array.0.2 }}</td>
</tr>
<tr>
<td class="hori">{{ array.1.0 }}</td>
<td class="vert hori">{{ array.1.1 }}</td>
<td class="hori">{{ array.1.2 }}</td>
</tr>
<tr>
<td>{{ array.2.0 }}</td>
<td class="vert">{{ array.2.1 }}</td>
<td>{{ array.2.2 }}</td>
</tr>
</table>
Here we are displaying each and every element of your matrix, one by one.
For eg: {{ array.0.1 }} means show element whose position is at 0th row, 1st col of your array.
EDIT 1: If you have lots of matrices or bigger range of matrix then definitely above solution is not at all efficient. But as your requirement is to have those 'vert' and 'hori' css classes only to specific table data cells, it become more difficult to achieve the desired result using for loops and if conditions, and implementing couple of for loops and dozens of if conditions isn't sensible if you are trying to apply this requirement only to one 3x3 matrix.
If you are okay with applying 'vert' and 'hori' css class to all table data cells, then the more elegant solution would be:
<table>
{% for row in array %}
<tr>
{% for cell in row %}
<td class="vert hori">{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
Upvotes: 1