menu.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package menu_service
  2. import (
  3. "fmt"
  4. "gfast/app/model/admin/cms_category"
  5. "gfast/library/utils"
  6. "github.com/gogf/gf/container/garray"
  7. "github.com/gogf/gf/frame/g"
  8. "github.com/gogf/gf/util/gconv"
  9. )
  10. type Menus struct {
  11. *cms_category.Entity
  12. Children []*Menus `json:"children"`
  13. }
  14. //获取导出菜单
  15. func GetNav(activeId uint64) (nav string, err error) {
  16. var menuList []*cms_category.Entity
  17. menuList, err = cms_category.GetList()
  18. if err != nil {
  19. return
  20. }
  21. if menuList != nil {
  22. //剔除隐藏的菜单
  23. menus := make([]*cms_category.Entity, 0, len(menuList))
  24. for _, v := range menuList {
  25. if v.Status == 1 {
  26. menus = append(menus, v)
  27. }
  28. }
  29. topIds := GetTopPidList(menus)
  30. topIds.Iterator(func(k int, v int) bool {
  31. nav += SetTreeMenu(menus, v, activeId, "sf-menu sf-arrows")
  32. return true
  33. })
  34. }
  35. return
  36. }
  37. //获取菜单树形结构
  38. func SetTreeMenu(menuList []*cms_category.Entity, pid int, activeId uint64, class string) string {
  39. parentId := gconv.Int64(pid)
  40. html := fmt.Sprintf(`<ul class="%s">`, class)
  41. //获取最顶级
  42. var topMenus g.Map
  43. menuListMap := make(g.List, len(menuList))
  44. for k, m := range menuList {
  45. menuListMap[k] = gconv.Map(m)
  46. }
  47. if activeId != 0 {
  48. topMenus = utils.FindTopParent(menuListMap, gconv.Int64(activeId), "parent_id", "id")
  49. }
  50. for k, v := range menuList {
  51. if v.ParentId == parentId {
  52. class := ""
  53. if topMenus != nil && topMenus["id"] == v.Id {
  54. class = "active"
  55. } else if activeId == v.Id {
  56. class = "active"
  57. } else if activeId == 0 && k == 0 {
  58. class = "active"
  59. }
  60. for _, vv := range menuList {
  61. if gconv.Uint64(vv.ParentId) == v.Id {
  62. class += " sf-with-ul"
  63. break
  64. }
  65. }
  66. url := fmt.Sprintf("/cms/list/%d", v.Id)
  67. if v.CateType == 3 {
  68. url = v.CateAddress
  69. }
  70. html += fmt.Sprintf(`<li><a href="%s" class="%s">%s</a>`, url, class, v.Name)
  71. html += SetTreeMenu(menuList, gconv.Int(v.Id), activeId, "sub-menu")
  72. html += "</li>"
  73. }
  74. }
  75. if html == "<ul>" {
  76. return ""
  77. }
  78. html += "</ul>"
  79. return html
  80. }
  81. //获取顶级菜单ID
  82. func GetTopPidList(menuList []*cms_category.Entity) (ids *garray.IntArray) {
  83. ids = garray.NewIntArray()
  84. for _, v1 := range menuList {
  85. tag := true
  86. for _, v2 := range menuList {
  87. if gconv.Uint64(v1.ParentId) == v2.Id {
  88. tag = false
  89. break
  90. }
  91. }
  92. if tag {
  93. ids.PushRight(gconv.Int(v1.ParentId))
  94. }
  95. }
  96. ids = ids.Unique()
  97. return
  98. }