I am new to jinja and flask
I am trying print all employees information
Users table is having Employee name, dept_id and role_id, code is below:
HTML:
<table>
<tr>
<th>Employee Name</th>
<th>Department Name</th>
<th>Employee Role</th>
</tr>
{% for emp in employees %}
{% set dept_name = depts[emp.dept_id] %}
{% set role_name = roles[emp.role_id] %}
<tr>
<td>{{ emp.name }}</td>
<td>{{ dept_name }}</td>
<td>{{ role_name }}</td>
</tr>
{% endfor %}
</table>
Python:
def display_employees():
employees = Users.query.all()
departments = Department.query.all()
depts = {}
roles = {2: "Manager", 3: "Employee"}
for dept in departments:
depts[dept.id] = dept.name
return render_template(
"display_employees.html", employees=employees, depts=depts, roles=roles
)
DB:
Department Data:
[("7", "Sales"), ("8", "IT")]
Users Data:
[("id", "Name", "Email", "role_id", "dept_id")]
[("2", "Anuj Kumar", "anuj.kumar@gmail.com", "2", "8")]
NOT ABLE TO DISPLAY dept_name and role_name
Please ask if I forgot to share any information.
Thanks in advance
I solved this by using multiple set statements
As it was 2 level accessing of variable
when I was trying depts.emp.dept_id
, it was saying that emp is not attribute of depts which is true
So, I did as below:
{% set emp_role_id, emp_dept_id = emp.role_id, emp.dept_id %}
{% set role_name, dept_name = roles[emp_role_id], depts[emp_dept_id] %}
It worked for me, thanks everyone for giving your inputs