link.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. from typing import Any, Callable, Union
  2. from ..client import Client
  3. from ..element import Element
  4. from .mixins.text_element import TextElement
  5. class Link(TextElement, component='link.js', default_classes='nicegui-link'):
  6. def __init__(self,
  7. text: str = '',
  8. target: Union[Callable[..., Any], str, Element] = '#',
  9. new_tab: bool = False,
  10. ) -> None:
  11. """Link
  12. Create a hyperlink.
  13. To jump to a specific location within a page you can place linkable anchors with `ui.link_target("name")`
  14. and link to it with `ui.link(target="#name")`.
  15. :param text: display text
  16. :param target: page function, NiceGUI element on the same page or string that is a an absolute URL or relative path from base URL
  17. :param new_tab: open link in new tab (default: False)
  18. """
  19. super().__init__(text=text)
  20. if isinstance(target, str):
  21. self._props['href'] = target
  22. elif isinstance(target, Element):
  23. self._props['href'] = f'#c{target.id}'
  24. elif callable(target):
  25. self._props['href'] = Client.page_routes[target]
  26. self._props['target'] = '_blank' if new_tab else '_self'
  27. class LinkTarget(Element):
  28. def __init__(self, name: str) -> None:
  29. """Link target
  30. Create an anchor tag that can be used as inner-page target for links.
  31. :param name: target name
  32. """
  33. super().__init__('a')
  34. self._props['name'] = name