search
HomeBackend DevelopmentGolangGin web application renders only one template

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

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}}

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 }}

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 }}

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
}

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)
}

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}}

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}}

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"}}

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
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
Choosing Between Golang and Python: The Right Fit for Your ProjectChoosing Between Golang and Python: The Right Fit for Your ProjectApr 19, 2025 am 12:21 AM

Golangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp

Golang: Concurrency and Performance in ActionGolang: Concurrency and Performance in ActionApr 19, 2025 am 12:20 AM

Golang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.

Golang vs. Python: Which Language Should You Learn?Golang vs. Python: Which Language Should You Learn?Apr 19, 2025 am 12:20 AM

Golang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.

Golang vs. Python: Performance and ScalabilityGolang vs. Python: Performance and ScalabilityApr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang vs. Other Languages: A ComparisonGolang vs. Other Languages: A ComparisonApr 19, 2025 am 12:11 AM

Go language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.

Golang and Python: Understanding the DifferencesGolang and Python: Understanding the DifferencesApr 18, 2025 am 12:21 AM

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang vs. C  : Assessing the Speed DifferenceGolang vs. C : Assessing the Speed DifferenceApr 18, 2025 am 12:20 AM

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang: A Key Language for Cloud Computing and DevOpsGolang: A Key Language for Cloud Computing and DevOpsApr 18, 2025 am 12:18 AM

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.