Conditionally execute multiple templates
php Xiaobian Yuzai introduces you to a powerful technology: conditionally executing multiple templates. When developing a website, we often need to dynamically load different template files based on different conditions. This is the application scenario of conditionally executing multiple templates. By using this technology, we can dynamically load corresponding template files based on the user's login status, permissions and other conditions, thereby achieving a more flexible and personalized website interface. This technology not only improves the scalability and maintainability of the website, but also provides users with a better user experience. In this article, we will introduce in detail how to use PHP to conditionally execute multiple templates to help you better apply it in actual projects.
Question content
I have a web page with two views, one for anonymous users and one for admin users. I want to show navigation bar only for admin users. Everything else remains the same for both user types.
Here's what I've tried so far
main.go
package main import ( "log" "net/http" "text/template" "github.com/julienschmidt/httprouter" ) func basicauth(h httprouter.handle, requireduser, requiredpassword string) httprouter.handle { return func(w http.responsewriter, r *http.request, ps httprouter.params) { // get the basic authentication credentials user, password, hasauth := r.basicauth() if hasauth && user == requireduser && password == requiredpassword { // delegate request to the given handle h(w, r, ps) } else { // request basic authentication otherwise w.header().set("www-authenticate", "basic realm=restricted") http.error(w, http.statustext(http.statusunauthorized), http.statusunauthorized) } } } func anonymous(w http.responsewriter, r *http.request, _ httprouter.params) { t, err := template.parsefiles("index.html") if err != nil { log.fatalln(err) } err = t.execute(w, map[string]string{"name": "anonymous"}) if err != nil { log.fatalln(err) } } func admin(w http.responsewriter, r *http.request, _ httprouter.params) { t, err := template.parsefiles("index.html", "admin.html") if err != nil { log.fatalln(err) } err = t.execute(w, map[string]string{"name": "admin"}) if err != nil { log.fatalln(err) } } func main() { user := "admin" pass := "1234" router := httprouter.new() router.get("/", anonymous) router.get("/admin/", basicauth(admin, user, pass)) log.fatal(http.listenandserve(":8080", router)) }
index.html
<!doctype html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{ .name }}</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script> function counter() { document.getelementbyid("x").innerhtml = "x: " + document.queryselectorall('.x').length; document.getelementbyid("y").innerhtml = "y: " + document.queryselectorall('.y').length; document.getelementbyid("z").innerhtml = "z: " + document.queryselectorall('.z').length; } </script> </head> <body onload="counter()"> {{ template "dashboard" }} <nav class="navbar fixed-bottom"> <div class="container-fluid nav-justified"> <span id="x" class="navbar-brand nav-item"></span> <span id="y" class="navbar-brand nav-item"></span> <span id="z" class="navbar-brand nav-item"></span> </div> </nav> </body> </html>
admin.html
{{ define "dashboard" }} <nav class="navbar"> <div class="container-fluid nav-justified"> <span class="nav-item"> <a class="navbar-brand" href="/a">a</a> </span> <span class="nav-item"> <a class="navbar-brand" href="/b">b</a> </span> <span class="nav-item"> <a class="navbar-brand" href="/c">c</a> </span> </div> </nav> {{ end }}
My assumption is that because I am not passing in the admin.html template when executing the template for the anonymous user, the dashboard template will not be parsed. However, I encountered this error:
template: index.html:18:14: executing "index.html" at <{{template "dashboard"}}>: template "dashboard" not defined
How to solve this problem, or is there a better way?
Solution
Use the if
operation to render conditionally dashboard
Template:
{{ if eq .name "admin" }} {{ template "dashboard" }} {{ end }}
Practice is to parse the template only once, rather than parsing it on every request:
package main import ( "log" "net/http" "sync" "text/template" "github.com/julienschmidt/httprouter" ) func BasicAuth(h httprouter.Handle, requiredUser, requiredPassword string) httprouter.Handle { return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { user, password, hasAuth := r.BasicAuth() if hasAuth && user == requiredUser && password == requiredPassword { h(w, r, ps) } else { w.Header().Set("WWW-Authenticate", "Basic realm=Restricted") http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) } } } func Anonymous(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { err := tmpl.Execute(w, map[string]string{"Name": "Anonymous"}) if err != nil { log.Fatalln(err) } } func Admin(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { err := tmpl.Execute(w, map[string]string{"Name": "Admin"}) if err != nil { log.Fatalln(err) } } var ( tmpl *template.Template tmplOnce sync.Once ) func main() { user := "admin" pass := "1234" tmplOnce.Do(func() { tmpl = template.Must(template.ParseFiles("index.html", "admin.html")) }) router := httprouter.New() router.GET("/", Anonymous) router.GET("/admin/", BasicAuth(Admin, user, pass)) log.Fatal(http.ListenAndServe(":8080", router)) }
The above is the detailed content of Conditionally execute multiple templates. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

The article discusses Go's reflect package, used for runtime manipulation of code, beneficial for serialization, generic programming, and more. It warns of performance costs like slower execution and higher memory use, advising judicious use and best

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization

The article discusses using table-driven tests in Go, a method that uses a table of test cases to test functions with multiple inputs and outcomes. It highlights benefits like improved readability, reduced duplication, scalability, consistency, and a
