Table of Contents
Question content
Register
Workaround
Home Backend Development Golang Gin web application renders only one template

Gin web application renders only one template

Feb 13, 2024 am 11:30 AM
go language

Gin Web 应用程序仅渲染一个模板

Gin is a lightweight web framework that is widely used in Go language web development. In Gin, web applications usually only need to render a template to complete the page display. This design allows developers to focus more on the implementation of business logic and simplifies the development process. In the opinion of PHP editor Xiaoxin, this feature of Gin not only improves development efficiency, but also reduces resource usage, making Web applications more efficient. At the same time, Gin also provides a wealth of middleware and plug-ins, providing developers with more scalability and flexibility. In short, Gin's simplicity and powerful features make it the preferred framework for many developers.

Question content

I have a Gin web application that contains multiple HTML templates based on a set of sections and a base template. The base template seems to render fine with the relevant parts, but my main view, login, index and registration are not rendering as expected. Whenever I access the HTTP endpoint of any of these, only the register view is rendered.

Is there something missing or misconfigured in the following files that prevents my route from rendering the requested page?

My project has the following structure.

├── app
...
│   ├── handlers
│   │   ├── general
│   │   │   └── general.go
│   │   └── routes.go
│   ├── main.go
│   ├── reloadDev.sh
│   ├── static
│   │   ├── css
│   │   ├── img
│   │   └── js
│   └── templates
│       ├── home
│       │   ├── index.tmpl.html
│       │   ├── login.tmpl.html
│       │   └── register.tmpl.html
│       ├── layouts
│       │   └── base.tmpl.html
│       └── partials
│           ├── footer.tmpl.html
│           ├── head.tmpl.html
│           └── navbar.tmpl.html
Copy after login

base.tmpl.html

{{ define "base" }}
<!DOCTYPE html>
<html lang="eng" data-bs-theme="dark">
    {{ template "head" . }}
    {{template "navbar" .}}
    <body>
    {{ block "content" . }}{{ end }}
    </body>
    {{template "footer" .}}
</html>
{{end}}
Copy after login

Register.tmpl.html

{{ template "base" . }}
{{ define "content" }}
<div class="container">
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <h1 id="Register">Register</h1>
            <form action="/register" method="post">
                <div class="mb-3">
                    <label for="username" class="form-label">Username</label>
                    <input type="text" name="username" id="username" class="form-control" placeholder="Username" required>
                </div>
                <div class="mb-3">
                    <label for="password" class="form-label">Password</label>
                    <input type="password" name="password" id="password" class="form-control" placeholder="Password" required>
                </div>
...SNIP...
                <button type="submit" class="btn btn-primary">Register</button>
            </form>
        </div>
    </div>
</div>
{{ end }}
Copy after login

index.tmpl.html (The structure of the login is the same as these two.)

{{ template "base" . }}
{{ define "title" }}Home{{ end }}
{{ define "content" }}
<div class="container">
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <p>Welcome to Astra Porta.</p>
            <p>Click <a href="https://www.php.cn/link/1b8e84dcae97ad25234484e38615c570">here</a> to login.</p>
        </div>
    </div>
</div>
{{ end }}
Copy after login

HTML templates are bundled with binaries using embed.FS.

//go:embed templates/partials/* templates/layouts/* templates/home/*
var files embed.FS

func main() {
    router := setupRouter()
    err := router.Run()
    if err != nil {
        panic(err)
    }
}

func setupRouter() *gin.Engine {
    router := gin.Default()
    subFS, e := fs.Sub(files, "templates")
    if e != nil {
        panic(e)
    }

tmpl := template.Must(template.ParseFS(
    subFS,
    "layouts/*.html",
    "partials/*.html",
    "home/*.html",
))
router.SetHTMLTemplate(tmpl)

router.StaticFS("/static", http.Dir("static"))

err := router.SetTrustedProxies(nil)
if err != nil {
    panic(err)
}
handlers.InitializeRoutes(&router.RouterGroup)
return router
}
Copy after login

The page is rendered in my application route. References here map to the file names of *.tmpl.html files.

func SiteIndex(c *gin.Context) {
    c.HTML(http.StatusOK, "index.tmpl.html", nil)
}

func GetRegister(c *gin.Context) {
    c.HTML(http.StatusOK, "register.tmpl.html", nil)
}

func GetLogin(c *gin.Context) {
    c.HTML(http.StatusOK, "login.tmpl.html", nil)
}
Copy after login

Workaround

For anyone else who encounters this problem. The solution pointed out by mkopriva in the comments is correct. I removed the base.tmpl.html and composed each view with the updated section and target page.

title

{{ define "header" }}
<!DOCTYPE html>
<html lang="eng" data-bs-theme="dark">
{{template "navbar" .}}
    <body>
    {{ block "content" . }}{{ end }}
        <head><meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
           ...SNIP...
            <title>App</title>
        </head>
{{end}}
Copy after login

footer

{{define "footer"}}

        <div class="container">
            <footer class="py-3 my-4" data-bs-theme="dark">
                <ul class="nav justify-content-center border-bottom pb-3 mb-3">
                    <li class="nav-item"><a href="/" class="nav-link px-2 text-body-secondary">Home</a></li>
                </ul>
                <p class="text-center text-body-secondary">© 2024 .</p>
            </footer>
        </div>
    </body>
</html>
{{end}}
Copy after login

Problematic Page

{{template "header"}}
<div class="container">
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <p>Welcome to Astra Porta.</p>
            <p>Click <a href="https://www.php.cn/link/1b8e84dcae97ad25234484e38615c570">here</a> to login.</p>
        </div>
    </div>
</div>
{{template "footer"}}
Copy after login

The above is the detailed content of Gin web application renders only one template. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

When using sql.Open, why does not report an error when DSN passes empty? When using sql.Open, why does not report an error when DSN passes empty? Apr 02, 2025 pm 12:54 PM

When using sql.Open, why doesn’t the DSN report an error? In Go language, sql.Open...

See all articles