22

Nested Property Access

From messy chaining to clean, Pythonic patterns

📋 The Data Structure

First, let's see what we're working with - a nested user profile object:

user_data = { 'id': , 'name': '', 'profile': { 'bio': '', 'preferences': { 'theme': '', 'notifications': { 'email': , 'push': } } }, 'stats': { 'posts': , 'followers': } }

Now let's learn how to access this data cleanly in StarHTML templates.

💡 Two Approaches: Messy vs Clean

There are two ways to access nested properties. See the difference:

# ❌ Hard to read, error-prone, and unmaintainable Span(data_text=user_data.profile.preferences.theme) Button(data_on_click=user_data.profile.preferences.notifications.email.set(~user_data.profile.preferences.notifications.email)) Span(data_text=user_data.profile.preferences.notifications['push']) Input(data_bind=user_data.profile.preferences.theme)
# ✅ Clean, readable, and maintainable profile = user_data.profile preferences = profile.preferences notifications = preferences.notifications # Now use clean references: Span(data_text=preferences.theme) Button(data_on_click=notifications.email.set(~notifications.email)) Input(data_bind=preferences.theme)

📍 Start Simple: Top-Level Properties

Begin with straightforward, top-level properties from our data structure:

👤 User ID:
📛 Name:
# Direct access to top-level properties user_data.id # Simple and clean user_data.name # No intermediate variables needed

🔗 Add One Level: Intermediate Variables

When you need nested data, extract logical sections:

📝 Bio:
🎨 Theme:
# Extract logical sections first profile = user_data.profile preferences = profile.preferences # Then use clean references profile.bio # Much cleaner! preferences.theme # Easy to read

📦 Group Related Data

Extract common parents for related properties:

📧 Email notifications:
🔔 Push notifications:
# Group related properties under common parent notifications = preferences.notifications # All notification properties are now clean notifications.email notifications['push'] # Bracket notation for reserved words

🧮 Advanced: Computed Properties

Combine intermediate signals with calculations:

📊 Posts:
👥 Followers:
🎯 Status:
# Use intermediate signals in calculations stats = user_data.stats # Complex expressions stay readable (stats.followers > 1000).if_('Influencer', 'Regular') (stats.followers > 1000).if_('(Popular!)', '')

🎮 Interactive Playground

Experiment with accessing and updating different properties:

Try these examples:

Update the value:

💡 Try clicking the examples above, then update values to see how changes affect the entire page!

Key Takeaways

Extract logical sections into variables for better readability
Use bracket notation for reserved words and dynamic keys
Group related properties under common parent objects
Keep expressions short and readable in templates
Follow Python naming conventions for maintainable code