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!

This article explains Go's package import mechanisms: named imports (e.g., import "fmt") and blank imports (e.g., import _ "fmt"). Named imports make package contents accessible, while blank imports only execute t

This article explains Beego's NewFlash() function for inter-page data transfer in web applications. It focuses on using NewFlash() to display temporary messages (success, error, warning) between controllers, leveraging the session mechanism. Limita

This article details efficient conversion of MySQL query results into Go struct slices. It emphasizes using database/sql's Scan method for optimal performance, avoiding manual parsing. Best practices for struct field mapping using db tags and robus

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

This article details efficient file writing in Go, comparing os.WriteFile (suitable for small files) with os.OpenFile and buffered writes (optimal for large files). It emphasizes robust error handling, using defer, and checking for specific errors.

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

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


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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
