search
HomeBackend DevelopmentGolangConditionally execute multiple templates

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&#160;protected]/dist/css/bootstrap.min.css" rel="stylesheet">
        <script src="https://cdn.jsdelivr.net/npm/[email&#160;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!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
String Manipulation in Go: Mastering the 'strings' PackageString Manipulation in Go: Mastering the 'strings' PackageMay 14, 2025 am 12:19 AM

Mastering the strings package in Go language can improve text processing capabilities and development efficiency. 1) Use the Contains function to check substrings, 2) Use the Index function to find the substring position, 3) Join function efficiently splice string slices, 4) Replace function to replace substrings. Be careful to avoid common errors, such as not checking for empty strings and large string operation performance issues.

Go 'strings' package tips and tricksGo 'strings' package tips and tricksMay 14, 2025 am 12:18 AM

You should care about the strings package in Go because it simplifies string manipulation and makes the code clearer and more efficient. 1) Use strings.Join to efficiently splice strings; 2) Use strings.Fields to divide strings by blank characters; 3) Find substring positions through strings.Index and strings.LastIndex; 4) Use strings.ReplaceAll to replace strings; 5) Use strings.Builder to efficiently splice strings; 6) Always verify input to avoid unexpected results.

'strings' Package in Go: Your Go-To for String Operations'strings' Package in Go: Your Go-To for String OperationsMay 14, 2025 am 12:17 AM

ThestringspackageinGoisessentialforefficientstringmanipulation.1)Itofferssimpleyetpowerfulfunctionsfortaskslikecheckingsubstringsandjoiningstrings.2)IthandlesUnicodewell,withfunctionslikestrings.Fieldsforwhitespace-separatedvalues.3)Forperformance,st

Go bytes package vs strings package: Which should I use?Go bytes package vs strings package: Which should I use?May 14, 2025 am 12:12 AM

WhendecidingbetweenGo'sbytespackageandstringspackage,usebytes.Bufferforbinarydataandstrings.Builderforstringoperations.1)Usebytes.Bufferforworkingwithbyteslices,binarydata,appendingdifferentdatatypes,andwritingtoio.Writer.2)Usestrings.Builderforstrin

How to use the 'strings' package to manipulate strings in Go step by stepHow to use the 'strings' package to manipulate strings in Go step by stepMay 13, 2025 am 12:12 AM

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Go strings package: how to improve my code?Go strings package: how to improve my code?May 13, 2025 am 12:10 AM

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

What are the most useful functions in the GO bytes package?What are the most useful functions in the GO bytes package?May 13, 2025 am 12:09 AM

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Mastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive GuideMastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive GuideMay 13, 2025 am 12:07 AM

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary

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 Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment