phpgogo-templatesgo-fibergo-html-template

Golang - Html Template : How do I create a Nav-item - Submenu? I couldn't find how to do it


I'm trying to switch from PHP to GO, but I'm stuck at one point, I ask for your help.

I have a table called Menu in the database. Here, menuid equal to 0 becomes the main menu. Those not equal to 0 depend on the written menuid. I want to draw the sub menu it is dependent on, but I can't do it, I'm stuck.

Table > Menu menu table

html enter image description here

Output > Instead of adding the sub menus one after the other, it adds each of them side by side and as a separate menu. enter image description here

My PHP Func. php func

PHP Output (working) php output

Instead of adding the sub menu one after the other , it adds each of them side by side and as a separate menu . I couldn't find how to do it.


Solution

  • I solved my problem.

    I implemented a structure like below. Anyone who needs it can copy it from here.

    package main
    
    import (
        "html/template"
        "log"
    
        "github.com/gofiber/fiber/v2"
        "gorm.io/driver/sqlite"
        "gorm.io/gorm"
    )
    
    type MenuItem struct {
        gorm.Model
        Title    string
        ParentID int
        URL      string
        SubMenu  []MenuItem `gorm:"-"`
    }
    
    var db *gorm.DB
    
    func main() {
        app := fiber.New()
    
        var err error
        db, err = gorm.Open(sqlite.Open("menu.db"), &gorm.Config{})
        if err != nil {
            log.Fatal(err)
        }
    
        db.AutoMigrate(&MenuItem{})
    
        app.Get("/", func(c *fiber.Ctx) error {
            menuItems := []MenuItem{}
            db.Where("parent_id = ?", 0).Find(&menuItems)
            for i := range menuItems {
                subMenuItems := []MenuItem{}
                db.Where("parent_id = ?", menuItems[i].ID).Find(&subMenuItems)
                menuItems[i].SubMenu = subMenuItems
            }
            return c.Render("index", fiber.Map{"MenuItems": menuItems})
        })
    
        app.Static("/static", "./static")
    
        app.Listen(":8080")
    }
    

    html

    <nav>
        <ul>
            {{ range $index, $item := .MenuItems }}
                <li><a href="{{ $item.URL }}">{{ $item.Title }}</a></li>
                {{ if $item.SubMenu }}
                    <ul>
                        {{ range $subIndex, $subItem := $item.SubMenu }}
                            <li><a href="{{ $subItem.URL }}">{{ $subItem.Title }}</a></li>
                        {{ end }}
                    </ul>
                {{ end }}
            {{ end }}
        </ul>
    </nav>