Prosenjit
Prosenjit

Reputation: 241

how to access dictionary items of list from webpy html file

# index.html

$def with (data)
    $for i in data: 
        <tbody>
        <tr>
        <td>$i</td>
        </tr>
        <tbody>

Here data contains a list such like

[
    {
        "id":1,
        "name":"Prosenjit Das",
        "log_date":"2019-03-02",
        "log_time":"12:10:12.247257",
        "login":null,
        "logout":null
    },
    {
        "id":2,
        "name":"Sudipto Rahman",
        "log_date":"2019-03-02",
        "log_time":"12:10:12.247257",
        "login":"11:26:45",
        "logout":"10:49:53"
    },
    {
        "id":3,
        "name":"Trump Khatun",
        "log_date":"2019-03-02",
        "log_time":"12:10:12.247257",
        "login":null,
        "logout":null
    }
]

I want to access every dictionary items the way we access into raw python code. But as like as python condition here doesn't work. Is there any way as if i can access those dict items? If not, so which way jinja2 can i implement into webpy?

Here you can see my all code to clarify more. https://pastebin.com/tB4CVXpn

Thanks.

Upvotes: 0

Views: 137

Answers (1)

pbuck
pbuck

Reputation: 4551

Couple things, first note your loop will repeat <tbody> and </tbody> each time, so you'll instead want something like:

<tbody>
$for i in data:
    <tr><td>$i</td></tr>
</tbody>

That's not all, as I think you're looking to put each attribute of the dict as a separate TD element.

So, instead of $i, using another loop:

<tbody>
$for i in data:
    <tr>
    $for x in ('id', 'name', 'log_date', 'login', 'logout'):
        <td>$i[x]</td>
    </tr>
</tbody>

Recall that dict is not sorted, so you'll need to explicitly list the attrbute names so you get them in the correct order.

Upvotes: 1

Related Questions