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.
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
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)) }
<!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>
{{ 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?
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!