SideBar.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. class SideBar:
  2. DIV: str = 'div'
  3. H1: str = 'h1'
  4. MORE: str = 'more'
  5. MORE_ITEMS_LENGTH = 3
  6. SHOULD_COMPRESS_HTML: bool = True
  7. def __init__(self,
  8. title: str,
  9. memu_items: [str],
  10. more: str = MORE,
  11. more_items_length: int = MORE_ITEMS_LENGTH,
  12. should_compress_html: bool = SHOULD_COMPRESS_HTML
  13. ) -> None:
  14. self.title = title
  15. self.more = more
  16. self.should_compress_html = should_compress_html
  17. self.memu_items = memu_items
  18. self.more_items_length = more_items_length
  19. def __len__(self):
  20. return len(self.memu_items)
  21. def __repr__(self):
  22. return f'SideBar: {len(self)} memu items'
  23. @classmethod
  24. def _header(cls, title: str) -> str:
  25. return cls._build_header(cls.H1, title)
  26. @classmethod
  27. def _body(cls, menu_items:[str], should_compress_html: bool) -> str:
  28. join_char = cls._get_split_char(should_compress_html)
  29. return join_char.join(
  30. list(cls._build_body(cls.DIV, menu_items))
  31. )
  32. @classmethod
  33. def _more(cls, more):
  34. return cls._build_more(cls.DIV, more)
  35. @staticmethod
  36. def _build_header(tag_name: str, title: str) -> str:
  37. return f'<{tag_name}>{title}</{tag_name}>'
  38. @staticmethod
  39. def _build_body(tag_name: str, menu_items: [str]) -> str:
  40. for menu_item in menu_items:
  41. yield f'<{tag_name}>{menu_item}</{tag_name}>'
  42. @staticmethod
  43. def _build_more(tag_name: str, text: str) -> str:
  44. return f'<{tag_name}>{text}</{tag_name}>'
  45. @staticmethod
  46. def _get_split_char(should_compress_html: bool) -> str:
  47. return '' if should_compress_html else '\n'
  48. def _is_few_items(self):
  49. return len(self) < self.more_items_length
  50. def build(self) -> str:
  51. header = self._header(self.title)
  52. body = self._body(self.memu_items,self.should_compress_html)
  53. footer = self._more(self.more) if self._is_few_items() else ''
  54. split_char = self._get_split_char(self.should_compress_html)
  55. html = split_char.join([header, body, footer])
  56. return html
  57. if __name__ == '__main__':
  58. side_bar = SideBar('DEMO SIDE BAR', ['item1', 'item2', 'item3', 'item4', 'item5'], should_compress_html=False, more_items_length=10)
  59. print(side_bar.build())