Showcase: Tab component and template-centric components #540
JuroOravec
started this conversation in
Show and tell
Replies: 1 comment 1 reply
-
Hi! Can I ask some questions about the code in tabs.py? The intent is trying to figure out if there's more we can do to simplify writing components like this:
|
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
With the recent additions, django-components is now getting closer to be on par with React and Vue in terms of templating capabilities!
What I mean is that now it's possible to write complex templates where components are fully defined in the template, meaning that most of the HTML attributes and templating can be colocated. Really excited about this! 🎉
Here's an example of what is now possible with django-components:
Which renders:
While it may not look like much at first, stop and think... How is it possible?!
With simple components, we would assume that each component only renders and inserts a string in its place. Yet, we see that the tab headers (e.g.
Tab 1
) are rendered in a different place than where they were defined.What actually happens is that the
tabs
component uses the information fromtab_item
components. This is actually a major improvement in how components can be written with django-components.Previously, to achieve this layout, I had to define the HTML for individual tabs in Python code, and then pass around the pre-rendered HTML as variables:
This new approach has multiple advantages:
For anyone curious, the source code is below:
tabs.py
tabs.html
The example above uses:
Component
class.html_attrs
and theprop:key=val
syntax to allow users to provide arbitrary HTML attributes.How it works is that:
tabs
component expects onlytab_item
components in it's slot.tabs
component "provides" an empty arraytab_item
component that is rendered inside thetabs
slot,tab_item
"injects" the array from the parenttabs
component. And at the end of rendering oftab_item
, using one of the hooks,tab_item
adds its own rendered content into thetabs
array, to which it still holds a reference.tabs
's slot is rendered, we use the postprocess hook. At this point, the "provided" array is populated with the rendered content oftab_items
._TabsImpl
. At this point, it's the same biz as before - we pass data as props, and component renders it.Beta Was this translation helpful? Give feedback.
All reactions