搜尋
首頁後端開發Golang有條件地執行多個模板
有條件地執行多個模板Feb 09, 2024 am 11:48 AM

有條件地執行多個模板

php小編魚仔為您介紹一種強大的技巧:有條件地執行多個範本。在開發網站時,我們常常需要根據不同的條件動態地載入不同的模板文件,這就是有條件地執行多個模板的應用程式場景。透過使用這種技術,我們可以根據使用者的登入狀態、權限等條件來動態地載入相應的模板文件,從而實現更靈活、個人化的網站介面。這種技術不僅提高了網站的可擴展性和可維護性,還能為使用者提供更好的使用體驗。在本文中,我們將詳細介紹如何使用php實作有條件地執行多個範本的方法,幫助您更好地應用於實際專案中。

問題內容

我有一個具有兩種視圖的網頁,一種用於匿名用戶,一種用於管理員用戶。我想僅為管理員用戶顯示導覽列。對於兩種使用者類型,其他一切都保持不變。

這是我迄今為止嘗試過的

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

我的假設是,因為我在為匿名使用者執行模板時沒有傳入 admin.html 模板,所以儀表板模板不會被解析。但是,我遇到了這個錯誤:

template: index.html:18:14: executing "index.html" at <{{template "dashboard"}}>: template "dashboard" not defined

如何解決這個問題,或是有更好的方法嗎?

解決方法

使用 if 操作有條件地渲染 dashboard 範本:

{{ if eq .name "admin" }} {{ template "dashboard" }} {{ end }}

實踐是只解析模板一次,而不是在每個請求時解析它:

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

以上是有條件地執行多個模板的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除
Go語言包導入:帶下劃線和不帶下劃線的區別是什麼?Go語言包導入:帶下劃線和不帶下劃線的區別是什麼?Mar 03, 2025 pm 05:17 PM

本文解釋了GO的軟件包導入機制:命名imports(例如導入“ fmt”)和空白導入(例如導入_ fmt; fmt;)。 命名導入使包裝內容可訪問,而空白導入僅執行t

Beego框架中NewFlash()函數如何實現頁面間短暫信息傳遞?Beego框架中NewFlash()函數如何實現頁面間短暫信息傳遞?Mar 03, 2025 pm 05:22 PM

本文解釋了Beego的NewFlash()函數,用於Web應用程序中的頁間數據傳輸。 它專注於使用newflash()在控制器之間顯示臨時消息(成功,錯誤,警告),並利用會話機制。 Lima

Go語言中如何將MySQL查詢結果List轉換為自定義結構體切片?Go語言中如何將MySQL查詢結果List轉換為自定義結構體切片?Mar 03, 2025 pm 05:18 PM

本文詳細介紹了MySQL查詢結果的有效轉換為GO結構切片。 它強調使用數據庫/SQL的掃描方法來最佳性能,避免手動解析。 使用DB標籤和Robus的結構現場映射的最佳實踐

如何編寫模擬對象和存根以進行測試?如何編寫模擬對象和存根以進行測試?Mar 10, 2025 pm 05:38 PM

本文演示了創建模擬和存根進行單元測試。 它強調使用接口,提供模擬實現的示例,並討論最佳實踐,例如保持模擬集中並使用斷言庫。 文章

如何定義GO中仿製藥的自定義類型約束?如何定義GO中仿製藥的自定義類型約束?Mar 10, 2025 pm 03:20 PM

本文探討了GO的仿製藥自定義類型約束。 它詳細介紹了界面如何定義通用功能的最低類型要求,從而改善了類型的安全性和代碼可重複使用性。 本文還討論了局限性和最佳實踐

Go語言如何便捷地寫入文件?Go語言如何便捷地寫入文件?Mar 03, 2025 pm 05:15 PM

本文詳細介紹了在GO中詳細介紹有效的文件,將OS.WriteFile(適用於小文件)與OS.openfile和緩衝寫入(最佳大型文件)進行比較。 它強調了使用延遲並檢查特定錯誤的可靠錯誤處理。

您如何在GO中編寫單元測試?您如何在GO中編寫單元測試?Mar 21, 2025 pm 06:34 PM

本文討論了GO中的編寫單元測試,涵蓋了最佳實踐,模擬技術和有效測試管理的工具。

如何使用跟踪工具了解GO應用程序的執行流?如何使用跟踪工具了解GO應用程序的執行流?Mar 10, 2025 pm 05:36 PM

本文使用跟踪工具探討了GO應用程序執行流。 它討論了手冊和自動儀器技術,比較諸如Jaeger,Zipkin和Opentelemetry之類的工具,並突出顯示有效的數據可視化

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前By尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能