Wonseok Choi
Wonseok Choi

Reputation: 139

Iterating through a nested dictionary API response as variables in Jinja2 template?

Scenario

I have an API GET request which filters a DB table for a company called "Cat Inc." and returns info of employees part of "Cat Inc":

[
  {
    "company": "Cat Inc."
  },
[
  {
    "id": 1,
    "name": "Bob"
  },
  {
    "id": 2,
    "name": "Cat"
  }
 ]
]

I have a plain-text Jinja2 template company.j2:

The company name is {{ company }}.

{% for employee in employees %}
  {{ employee.name }} is part of the company with ID of {{ employee.id }}
{% endfor %}

And would ultimately like to return this:

The company name is Cat Inc.

Bob is part of the company with ID of 1 
Cat is part of the company with ID of 2

I've set the API @get request to return company info and employee info separately as list type variables, and following the docs, I tried something like this:

@get("/{company_id}", response_class=PlainTextResponse)
async def generate_template(company_id: int, request: Request):

     company = *<uses some function to filter to find Cat Inc.'s company_id>*

     employees = *<uses some function to find employees where company_id = Cat Inc.company_id>*

return templates.TemplateResponse("company.j2", {"request": Request, 
                                  "company": company.company, 
                                  "employees": employees.employee})

What I seem to return in the API request is:

The company name is Cat Inc.

And that is it. The for loop within the Jinja2 template gets ignored.

Upvotes: 0

Views: 93

Answers (1)

Wonseok Choi
Wonseok Choi

Reputation: 139

Credit to Chris in the comments section of the question above:

Changing the API response context for the template to take the entire dict instead of trying to specify the k/v pair of the dict that was required itself:

@get("/{company_id}", response_class=PlainTextResponse)
async def generate_template(company_id: int, request: Request):

     company = # *<uses some function to filter to find Cat Inc.'s company_id>*

     employees = # *<uses some function to find employees where company_id = Cat Inc.company_id>*

     return templates.TemplateResponse("company.j2", {"request": request, 
                                  "company": company.company, 
                                  "employees": employees})

And I was able to iterate through the list no problem.

Upvotes: 1

Related Questions