golang template HTML動態模板解析實現

使用場景: 我們希望在模板里面動態解析指定的模板文件。

這個似乎使用go語言的模板嵌套 template 可以實現,不過模板嵌套聲明里面是不支持使用變量的, 如:{{template "模板文件名" .}}? 這里的"模板文件名"不能使用變量,原因我們另外分析, 所以只能是靜態嵌套其他模板,不能實現動態嵌套其他模板!

golang動態模板解析實現思路

? ? ? ?要實現模板文件的動態解析, 我們可以通過在自定義模板函數的方式來實現。即 這個函數接收一個 模板文件變量 和模板解析參數 然后將模板文件解析為 HTML后返回給調用模板,這樣就實現了模板的動態解析。 【ps: 如果你有更好的思路,歡迎反饋分享 :)】

? ? ? ??

golang HTML動態模板解析實現代碼 示例

import ("bytes""html/template""path/filepath""github.com/spf13/viper" // 配置信息解析,可以使用其他你喜歡的
)// 獲取所有自定義模板函數
func GetFuncs() template.FuncMap {// fmap map[string]anyreturn template.FuncMap{"TplInclude":  TplInclude,}
}// 動態模板解析函數 將指定的模板文件渲染為html內容后返回
//
//	tplFile 模板文件 這個可以是相對exe所在文件夾的路徑 或者絕對路徑
//	datas 可選參數  要應用到模板文件中的數據 通常為map格式
//
// 返回可直接渲染頁面的 template.HTML 格式的字符串
// @author: TekinTian <tekinTian@gmail.com>
// @see https://dev.tekin.cn
func TplInclude(tplFile string, datas ...interface{}) template.HTML {var data interface{} // 應用到模板中的數據,默認空if len(datas) > 0 {data = datas[0] // 從可選參數中獲取}// 從配置文件中獲取分隔符delss := viper.GetStringSlice("viewer.delimiters")if len(delss) != 2 {delss = []string{"", ""} // 使用默認的分隔符,這里留空go最后解析的時候就會使用默認的分隔符 {{ }} 詳情src/text/template/parse/lex.go}// 獲取*template.Template對象 注意如果用到了自定義分隔符,自定義函數,則需要再這里重新注冊t := template.New(tplFile).Delims(delss[0], delss[1]).Funcs(GetFuncs())// 解析模板文件 注意這里的模板文件路徑必須是相對于exe運行文件所在的路徑 或者 絕對路徑tpl, err := t.ParseFiles(filepath.Join("templates", tplFile))if err != nil {return template.HTML(err.Error())}// 新建一個字符串緩存 writer, 解析后的模板內容將寫入到這里// 這里如果是直接輸出到瀏覽器的話用瀏覽器的writer即可, gin的輸出writer為 c.Writer// 我們這里不直接輸出到瀏覽器,而是輸出到模板文件中,所以用這個自定義的writer接收后轉為字符串輸出到模板中.buf := bytes.NewBufferString("")// 渲染模板if err := tpl.Execute(buf, data); err == nil {return template.HTML(buf.String()) // 將緩存中的所有數據以html格式放回 注意必須是template.HTML格式 否則頁面不會被解析} else {return template.HTML(err.Error())}
}

總結

動態模板解析這里的關鍵點就是如何將指定的模板文件解析為HTML字符串,一般我們常見的就是直接將模板文件解析后輸出到瀏覽器, 而這里是將模板文件解析后返回HTML格式的字符串,這就需要我們使用自定義的writer來接收模板解析后的內容,然后將這些內容返回, 注意這里在返回的時候必須使用?template.HTML 類型, 否則你返回的字符串將是被轉碼后的html,是不會被瀏覽器渲染的。

附?template包中定義的返回類型參考

我們上面就用到了下面的這個 HTML類型, 他其實就是一個string類型的類型定義, 當然如果我們希望實現動態渲染css,js 等其他內容,也需要使用下面定義的對應的類型才行哦。

package template// Strings of content from a trusted source.
type (// CSS encapsulates known safe content that matches any of://   1. The CSS3 stylesheet production, such as `p { color: purple }`.//   2. The CSS3 rule production, such as `a[href=~"https:"].foo#bar`.//   3. CSS3 declaration productions, such as `color: red; margin: 2px`.//   4. The CSS3 value production, such as `rgba(0, 0, 255, 127)`.// See https://www.w3.org/TR/css3-syntax/#parsing and// https://web.archive.org/web/20090211114933/http://w3.org/TR/css3-syntax#style//// Use of this type presents a security risk:// the encapsulated content should come from a trusted source,// as it will be included verbatim in the template output.CSS string// HTML encapsulates a known safe HTML document fragment.// It should not be used for HTML from a third-party, or HTML with// unclosed tags or comments. The outputs of a sound HTML sanitizer// and a template escaped by this package are fine for use with HTML.//// Use of this type presents a security risk:// the encapsulated content should come from a trusted source,// as it will be included verbatim in the template output.HTML string// HTMLAttr encapsulates an HTML attribute from a trusted source,// for example, ` dir="ltr"`.//// Use of this type presents a security risk:// the encapsulated content should come from a trusted source,// as it will be included verbatim in the template output.HTMLAttr string// JS encapsulates a known safe EcmaScript5 Expression, for example,// `(x + y * z())`.// Template authors are responsible for ensuring that typed expressions// do not break the intended precedence and that there is no// statement/expression ambiguity as when passing an expression like// "{ foo: bar() }\n['foo']()", which is both a valid Expression and a// valid Program with a very different meaning.//// Use of this type presents a security risk:// the encapsulated content should come from a trusted source,// as it will be included verbatim in the template output.//// Using JS to include valid but untrusted JSON is not safe.// A safe alternative is to parse the JSON with json.Unmarshal and then// pass the resultant object into the template, where it will be// converted to sanitized JSON when presented in a JavaScript context.JS string// JSStr encapsulates a sequence of characters meant to be embedded// between quotes in a JavaScript expression.// The string must match a series of StringCharacters://   StringCharacter :: SourceCharacter but not `\` or LineTerminator//                    | EscapeSequence// Note that LineContinuations are not allowed.// JSStr("foo\\nbar") is fine, but JSStr("foo\\\nbar") is not.//// Use of this type presents a security risk:// the encapsulated content should come from a trusted source,// as it will be included verbatim in the template output.JSStr string// URL encapsulates a known safe URL or URL substring (see RFC 3986).// A URL like `javascript:checkThatFormNotEditedBeforeLeavingPage()`// from a trusted source should go in the page, but by default dynamic// `javascript:` URLs are filtered out since they are a frequently// exploited injection vector.//// Use of this type presents a security risk:// the encapsulated content should come from a trusted source,// as it will be included verbatim in the template output.URL string// Srcset encapsulates a known safe srcset attribute// (see https://w3c.github.io/html/semantics-embedded-content.html#element-attrdef-img-srcset).//// Use of this type presents a security risk:// the encapsulated content should come from a trusted source,// as it will be included verbatim in the template output.Srcset string
)

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/37666.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/37666.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/37666.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

LeetCode 2710.移除字符串中的尾隨零:模擬

【LetMeFly】2710.移除字符串中的尾隨零&#xff1a;模擬 力扣題目鏈接&#xff1a;https://leetcode.cn/problems/remove-trailing-zeros-from-a-string/ 給你一個用字符串表示的正整數 num &#xff0c;請你以字符串形式返回不含尾隨零的整數 num 。 示例 1&#xff1a; 輸…

Apache Kylin資源管理全指南:優化你的大數據架構

標題&#xff1a;Apache Kylin資源管理全指南&#xff1a;優化你的大數據架構 摘要 Apache Kylin是一個開源的分布式分析引擎&#xff0c;旨在為大規模數據集提供高性能的SQL查詢能力。在Kylin中進行有效的資源管理對于確保查詢性能和系統穩定性至關重要。本文將詳細介紹如何…

leetcode 133雙周賽 統計逆序對的數目「dp」「前綴和優化」

3193. 統計逆序對的數目 題目描述&#xff1a; 給定一個長度為n的二維數組 r e re re&#xff0c;其中 r e [ i ] [ i d i , c n t i ] re[i] [id_i, cnt_i] re[i][idi?,cnti?]&#xff0c;求存在多少個全排列perm滿足對所有的 r e [ i ] re[i] re[i]都有 p e r m [ 0.. …

Bayes分類器設計

本篇文章是博主在人工智能等領域學習時&#xff0c;用于個人學習、研究或者欣賞使用&#xff0c;并基于博主對人工智能等領域的一些理解而記錄的學習摘錄和筆記&#xff0c;若有不當和侵權之處&#xff0c;指出后將會立即改正&#xff0c;還望諒解。文章分類在AI學習筆記&#…

東方博宜 OJ 1201-1300

目錄 1268&#xff1a;【基礎】高精度加法 1269&#xff1a;【基礎】高精度減法 1280&#xff1a;【基礎】求 2 的 n 次方 1281&#xff1a;【基礎】求 222222?222?2 1285:【基礎】計算 N 的階乘 1286&#xff1a;【基礎】高精度乘單精度 1287&#xff1a;【基礎】高精…

第一百三十三節 Java數據類型教程 - Java基本數據類型

Java數據類型教程 - Java基本數據類型 Java定義了八種基本類型的數據:byte&#xff0c;short&#xff0c;int&#xff0c;long&#xff0c;char&#xff0c;float&#xff0c;double和boolean。 基本類型通常被稱為簡單類型。 這些可以分為四組: Integers - 包括byte&#x…

求推薦幾款http可視化調試工具?

Postman 非常流行的API調試工具&#xff0c;適用于構建、測試和文檔化APIs。它支持各種HTTP方法&#xff0c;有強大的集合和環境管理功能&#xff0c;以及代碼生成能力。 BB-API 是一款旨在提升開發效率的工具&#xff0c;它專注于提供簡約、完全免費且功能強大的HTTP模擬請…

目標檢測算法

一、緒論 1.1 目標檢測算法的定義和背景 1.2 目標檢測算法在計算機視覺領域的重要性 二、目標檢測算法的發展歷程 2.1 傳統目標檢測算法 2.2 基于深度學習的目標檢測算法 2.3 目標檢測算法的評價指標 三、目標檢測算法的關鍵技術 3.1 區域建議網絡(RPN) 3.2 卷積神經…

springmvc快速上手

一、創建工程 1、創建maven工程&#xff0c;添加maven-archetype-webapp模版 2、添加依賴 <properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.co…

每日一題——Python實現PAT乙級1059 C語言競賽(舉一反三+思想解讀+逐步優化)四千字好文

一個認為一切根源都是“自己不夠強”的INTJ 個人主頁&#xff1a;用哲學編程-CSDN博客專欄&#xff1a;每日一題——舉一反三Python編程學習Python內置函數 Python-3.12.0文檔解讀 目錄 我的寫法 時間復雜度分析 空間復雜度分析 代碼優化建議 總結 我要更強 優化方法…

macos Darwin安裝faiss-cpu

文章目錄 macos 使用brew instll fass, 后python3.12執行引用faiss包功能出現的問題 安裝時遇到問題如下 ModuleNotFoundError Traceback (most recent call last) File ~/Src/ai/framework/langchain/.venv/lib/python3.12/site-packages/langchain_co…

Spring事務的實現

Spring事務的實現分為編程式事務和聲明式事務。 編程式事務 編程式事務管理需要開發者在代碼中顯式地調用事務管理相關的方法,如`beginTransaction()`、`commit()`和`rollback()`等。在Spring中,通常通過以下兩種方式來實現編程式事務: 使用`TransactionTemplate`,`Tran…

macOS 安裝redis

安裝Redis在macOS上通常通過Homebrew進行&#xff0c;Homebrew是macOS上一個流行的包管理器。以下是安裝Redis的步驟&#xff1a; 一 使用Homebrew安裝Redis 1、安裝Homebrew&#xff08;如果尚未安裝&#xff09;&#xff1a; 打開終端&#xff08;Terminal&#xff09;并執…

.NET周刊【6月第4期 2024-06-23】

國內文章 C#.Net筑基-集合知識全解 https://www.cnblogs.com/anding/p/18229596 .Net中提供了數組、列表、字典等多種集合類型&#xff0c;分為泛型和非泛型集合。泛型集合具有更好的性能和類型安全性。集合的基礎接口包括IEnumerator、IEnumerable、ICollection、IList、ID…

Gradio 4.37.1官方教程二:Blocks

文章目錄 一、Blocks及事件監聽器1.1 Blocks結構1.2 事件監聽器的類型1.3 多數據流1.4 多輸入組件1.5 多輸出組件1.6 更新組件配置1.7 添加示例1.8 連續運行事件1.9 持續運行事件1.9.1 every參數1.9.2 load方法1.9.3 change方法 1.10 收集事件數據1.11 綁定多個觸發器到同一函數…

基于線調頻小波變換的一維時間序列時頻分析方法(MATLAB)

在機械故障診斷領域,振動信號的處理常采用以快速傅立葉變換為基礎的相關分析、幅值分析、頻譜分析等時域和頻域分析方法。但經典的FFT存在固有缺點,即它雖然在頻域范圍內是完全局部化的,但是它不包含任何時域信息,因而不適于分析非平穩信號。近年來涌現的各種時頻分析方法(短時…

【刷題】初步認識深搜(DFS)

送給大家一句話&#xff1a; 擁有希望的人&#xff0c;和漫天的星星一樣&#xff0c;是永遠不會孤獨的。 -- 《星游記》 初步認識深搜&#xff08;DFS&#xff09; dfs算法二叉樹中的深搜Leetcode 129. 求根節點到葉節點數字之和題目描述算法思路 Leetcode 814. 二叉樹剪枝題…

Redis-實戰篇-緩存更新策略(內存淘汰、超時剔除、主動更新)

文章目錄 1、緩存更新策略1.1、內存淘汰1.2、超時剔除1.3、主動更新 2、業務場景&#xff1a;3、主動更新在企業中業務實現有三種方式3.1、Cache Aside Pattern3.1.1、操作緩存和數據庫時有三個問題需要考慮&#xff1a;3.1.1.1、刪除緩存還是更新緩存&#xff1f;3.1.1.2、如何…

數據同步軟件有哪些

數據同步軟件有哪些呢&#xff1f;隨著企業規模的擴大&#xff0c;企業數據也積累得越來越多&#xff0c;萬一發生宕機風險&#xff0c;那么這個損失將不可估量。所以為了容災備用&#xff0c;我們往往需要將數據同步到另一臺備胎服務器上&#xff0c;進行冗余。 那么需要同步的…

centos7.9 python3環境(virtualenv)搭建及所遇錯誤

人望山&#xff0c;魚窺荷&#xff0c;真正喜歡想要的&#xff0c;沒有一樣可以輕易得到。 目錄 # 1. 解決版本沖突問題--建議不要跳過(一定要查看軟鏈接是否鏈接正確) # 2. python3(virtualenv)環境搭建 # 3. virtualenv常用命令 # 4. 所遇錯誤解析 ## 4.1 遇到 No modul…