GO:借助html/template實現(xiàn)include子模板

不引入liquid支持庫,借助原有的html/template來支持include子模板功能。

思路:

  1. 模仿Django,默認(rèn)從templates文件夾下讀取模板,已經(jīng)取到的模板加入到map結(jié)構(gòu)的簡單cache中緩存
  2. 利用正則表達(dá)式在模板中發(fā)現(xiàn) {% include xxx %}時,將其作為一個文件遞歸加載到當(dāng)前模板中來,如果加載失敗(如文件不存在等), 那么將其保持原樣
  3. 利用html/template完成變量等的載入

規(guī)定格式時不能使用{{}}這種,因為template會認(rèn)為這是一條它支持的指令,一旦在第2步中加載失敗,就會保持原樣,繼續(xù)傳遞到template parser中去。

另外需要設(shè)置一個觀察值,在進行遞歸include時防止出現(xiàn)遞歸包含自己的死循環(huán)。

代碼實現(xiàn):

func RenderWithTemplate(writer io.Writer, templateName string, data map[string]interface{}) error {
    rawTemplate, err := LoadTemplate(templateName)
    if err != nil {
        return err
    }
    tmpl, err := template.New("new").Parse(rawTemplate)
    if err != nil {
        return err
    }
    return tmpl.Execute(writer, data)
}

var TemplateCache map[string]string = nil
var gRecursiveLoadTemplateCount = 0
// Load template with file name templateName under 'templates' dir
// If it contains {% include xxx %}, it will load content of that
// template into current template.
// **Note**: template name inside include directive should not be wrapped with ''
func LoadTemplate(templateName string) (string, error) {
    if result, ok := TemplateCache[templateName]; ok {
        return result, nil
    }

    templatePath := "templates/" + templateName
    file, err := os.Open(templatePath)
    if err != nil {
        return "", err
    }

    stat, err := file.Stat()
    if err != nil {
        return "", err
    }

    buffer := make([]byte, stat.Size())
    _, err = file.Read(buffer)
    if TemplateCache == nil {
        TemplateCache = make(map[string]string)
    }
    rawTemplate := string(buffer)
    re := regexp.MustCompile("{%\\s*include\\s+(.*?)\\s*%}")
    matches := re.FindAllStringSubmatchIndex(rawTemplate, -1)
    if len(matches) > 0 {
        newTemplate := ""
        start := 0
        for _, m := range matches {
            if len(m) == 4 {
                newTemplate += rawTemplate[start:m[0]]
                includeName := rawTemplate[m[2]:m[3]]

                gRecursiveLoadTemplateCount ++
                if gRecursiveLoadTemplateCount > 10 {
                    log.Fatal("Possible dead include loop in file: ", templateName)
                }
                includedTemplate, err := LoadTemplate(includeName)
                gRecursiveLoadTemplateCount --

                if err != nil {
                    fmt.Println("Failed to include file ", includeName, " from ", templateName, "err:", err)
                    includedTemplate = rawTemplate[m[0]:m[1]]  // Keep it as original
                }
                start = m[1]
                newTemplate += includedTemplate
            }
        }
        if start < len(rawTemplate) {
            newTemplate += rawTemplate[start:]
        }
        rawTemplate = newTemplate
    }
    TemplateCache[templateName] = rawTemplate
    return rawTemplate, nil
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,551評論 19 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,677評論 18 399
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,021評論 25 709
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,272評論 6 342
  • 一個人的眼淚
    SophiaWHAN閱讀 100評論 0 0

友情鏈接更多精彩內(nèi)容