Когда я перемещаюсь в/вокруг но содержимое остается таким же, как и домашняя страница (/) вместо того, чтобы показывать правильное содержание страницы.
Структура проекта
Код: Выделить всё
/app
/handlers
home.go
about.go
/views
renderer.go
/templates
/layouts
main.html
/pages
index.html
about.html
main.go
< /code>
реализация кода
main.go (точка входа) < /p>
package main
import (
"app/handlers"
"app/views"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
func main() {
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Renderer = views.NewRenderer()
e.GET("/", handlers.Home)
e.GET("/about", handlers.About)
e.Static("/static", "static")
e.Logger.Fatal(e.Start(":8080"))
}
Код: Выделить всё
package views
import (
"html/template"
"io"
"path/filepath"
"strings"
"github.com/labstack/echo/v4"
)
type TemplateRenderer struct {
templates *template.Template
}
func NewRenderer() *TemplateRenderer {
funcMap := template.FuncMap{
"dict": func(values ...interface{}) map[string]interface{} {
if len(values)%2 != 0 {
panic("invalid dict call")
}
dict := make(map[string]interface{}, len(values)/2)
for i := 0; i < len(values); i += 2 {
key, ok := values[i].(string)
if !ok {
panic("dict keys must be strings")
}
dict[key] = values[i+1]
}
return dict
},
}
tmpl := template.New("").Funcs(funcMap)
layoutGlob := filepath.Join("templates", "layouts", "*.html")
pagesGlob := filepath.Join("templates", "pages", "*.html")
tmpl = template.Must(tmpl.ParseGlob(layoutGlob))
tmpl = template.Must(tmpl.ParseGlob(pagesGlob))
normalizedTemplates := template.New("").Funcs(funcMap)
for _, t := range tmpl.Templates() {
if t.Tree == nil || t.Tree.Root == nil {
continue
}
name := t.Name()
if strings.HasPrefix(name, "pages/") {
name = strings.TrimPrefix(name, "pages/")
}
name = strings.TrimSuffix(name, ".html")
_, err := normalizedTemplates.New(name).Parse(t.Tree.Root.String())
if err != nil {
panic("Failed to normalize template names: " + err.Error())
}
}
return &TemplateRenderer{
templates: normalizedTemplates,
}
}
func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return t.templates.ExecuteTemplate(w, name, data)
}
Код: Выделить всё
package handlers
import (
"net/http"
"github.com/labstack/echo/v4"
)
func Home(c echo.Context) error {
return c.Render(http.StatusOK, "index", map[string]interface{}{})
}
Код: Выделить всё
package handlers
import (
"net/http"
"github.com/labstack/echo/v4"
)
func About(c echo.Context) error {
return c.Render(http.StatusOK, "about", map[string]interface{}{})
}
templates/layouts/main.html (Mayout)
Код: Выделить всё
{{ define "layout" }}
{{ block "title" . }}{{ if .title }}{{ .title }} | Application{{ else }}Application{{ end }}{{ end }}
[url=/]Home[/url] | [url=/about]About[/url]
{{ template "content" . }}
{{ end }}
Код: Выделить всё
{{ template "layout" (dict "title" "Home") }}
{{ define "content" }}
Welcome to the Home Page
This is a simple multi-page app with Echo.
{{ end }}
Код: Выделить всё
{{ template "layout" (dict "title" "About") }}
{{ define "content" }}
About
This is a simple multi-page app with Echo.
{{ end }}
/wud vand index.html Inside Mayout/main.html.
/about arender arder able.html Inside Mayout/main.html.
Фактическое поведение
/работает, как и ожидалось. /> Возможная проблема
Я подозреваю, что {{template "Mayout" (Dict "Title" "Oble")}} in about.html вызывает макет напрямую и делает содержимое "index.html" вместо его Собственный.
Подробнее здесь: https://stackoverflow.com/questions/794 ... ent-routes
Мобильная версия