bindings_documentation.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from nicegui import ui
  2. from ..documentation_tools import text_demo
  3. def main_demo() -> None:
  4. """Bindings
  5. NiceGUI is able to directly bind UI elements to models.
  6. Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
  7. Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
  8. To define a one-way binding use the `_from` and `_to` variants of these methods.
  9. Just pass a property of the model as parameter to these methods to create the binding.
  10. """
  11. class Demo:
  12. def __init__(self):
  13. self.number = 1
  14. demo = Demo()
  15. v = ui.checkbox('visible', value=True)
  16. with ui.column().bind_visibility_from(v, 'value'):
  17. ui.slider(min=1, max=3).bind_value(demo, 'number')
  18. ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(demo, 'number')
  19. ui.number().bind_value(demo, 'number')
  20. date = '2023-01-01'
  21. def more() -> None:
  22. @text_demo('Bind to dictionary', '''
  23. Here we are binding the text of labels to a dictionary.
  24. ''')
  25. def bind_dictionary():
  26. data = {'name': 'Bob', 'age': 17}
  27. ui.label().bind_text_from(data, 'name', backward=lambda n: f'Name: {n}')
  28. ui.label().bind_text_from(data, 'age', backward=lambda a: f'Age: {a}')
  29. ui.button('Turn 18', on_click=lambda: data.update(age=18))
  30. @text_demo('Bind to variable', '''
  31. Here we are binding the value from the datepicker to a bare variable.
  32. Therefore we use the dictionary `globals()` which contains all global variables.
  33. This demo is based on the [official datepicker example](https://nicegui.io/documentation/date#input_element_with_date_picker).
  34. ''')
  35. def bind_variable():
  36. # date = '2023-01-01'
  37. with ui.input('Date').bind_value(globals(), 'date') as date_input:
  38. with ui.menu() as menu:
  39. ui.date(on_change=lambda: ui.notify(f'Date: {date}')).bind_value(date_input)
  40. with date_input.add_slot('append'):
  41. ui.icon('edit_calendar').on('click', menu.open).classes('cursor-pointer')