I write this article in 2023/04/05
After my personal testing, The fixed code is running well on `pynecone==0.1.20` and `pynecone==0.1.21`
[TOC]
# pynecone Card layout by pc.grid + pc.foreach
## Original Code (cannot use well by pc.forech)
## Fixed Code to for the pc.foreach()
The basic example codeis from Mert Arda Asar on pynecone discord
```python=
import pynecone as pc
def show_items(item):
return pc.box(
pc.text(item),
bg="lightgreen"
)
class ExampleState(pc.State):
my_objects = [["item1", "desc1"], ["item2", "desc2"]]
print(my_objects)
def home():
homeContainer = pc.container(
pc.hstack(
pc.container(
# watch list
pc.vstack(
pc.container(h="20px"),
pc.hstack(
pc.heading("Example List", size="md"),
),
pc.grid(
pc.foreach(ExampleState.my_objects, show_items),
template_columns="repeat(5, 1fr)",
h="20vh",
width="100%",
gap=4,
),
justifyContent="start",
align_items="start",
),
height="100vh",
maxWidth="auto",
),
bg="#e8e5dc",
),
)
return homeContainer
app = pc.App(state=ExampleState)
app.add_page(home, route="/")
app.compile()
```
The problem of this code is that we cannot use
the item as list[list] or list[dict].
The following is the code that can run.
Yes, It's look like pc.foreach need to define something like class `MyObject(pc.Model, table=True):`
```python=
import pynecone as pc
class MyObject(pc.Model, table=True):
title:str
desc:str
def __init__(self, title, desc):
self.title = title
self.desc = desc
def __repr__(self) -> str:
return "("+self.title+","+self.desc+")"
def show_object(object:MyObject):
return pc.box(
pc.vstack(
pc.hstack(
pc.text(
"title:",
font_size="1em",
),
pc.text(
object.title,
font_size="1em",
),
),
pc.hstack(
pc.text(
"desc:",
font_size="1em",
),
pc.text(
object.desc,
font_size="1em",
),
),
),
bg="lightgreen"
)
class ExampleState(pc.State):
# my_objects = [{"item":"item1", "desc":"desc1"}, {"item":"item2", "desc":"desc2"}]
"""
my_objects:list[MyObject] = [
MyObject("title1", "desc1"),
MyObject("title2", "desc2"),
]
"""
# generate objects by loop
my_objects:list[MyObject] = [ MyObject("title"+str(i), "desc"+str(i)) for i in range(37)]
def home():
homeContainer = pc.container(
pc.hstack(
pc.container(
# watch list
pc.vstack(
pc.container(h="20px"),
pc.hstack(
pc.heading("Example List", size="md"),
),
pc.grid(
#pc.foreach(ExampleState.my_objects, show_items),
pc.foreach(ExampleState.my_objects, show_object),
template_columns="repeat(5, 1fr)",
h="20vh",
width="100%",
gap=4,
),
justifyContent="start",
align_items="start",
),
height="100vh",
maxWidth="auto",
),
bg="#e8e5dc",
),
)
return homeContainer
app = pc.App(state=ExampleState)
app.add_page(home, route="/")
app.compile()
```
## running result
