V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
vinsec

求助 Golang 如何渲染已有模板但不直接返回呢

  •  1
     
  •   vinsec · Feb 20, 2020 · 2207 views
    This topic created in 2258 days ago, the information mentioned may be changed or developed.
    func Render_(tmp string,ins Instance)[]byte{
    	// tmp 为已定义模板的路径 如 "templates/http.tmpl"
            tpl,err := template.ParseFiles(tmp)
    	
            if err != nil{
    		log.Fatal(err)
    	}
    	
    	data := ins
    	var buf bytes.Buffer
    	if err := tpl.ExecuteTemplate(&buf,tmp,data); err != nil {
    		log.Fatal(err)
    	}
    	return []byte(buf.String())
    	//fmt.Println(buf.String())
    
    }
    

    传入的 ins 对象包括三个属性,装载到已有的模板中,模板里的待渲染的变量是这 3 个的子集(有些模板有 1 个 有些有 2 个)。 请问用原生 template 库该如何实现呢 我上面写的好像实现不了 报 “templates/http.tmpl” undefied

    2 replies    2020-02-26 14:48:05 +08:00
    wa8n
        1
    wa8n  
       Feb 21, 2020
    ExecuteTemplate,第二个参数是模板文件名,传"http.tmpl"

    https://gist.github.com/wangsongyan/f9e187b8f5a7933d5c61d0dab68c56db
    vinsec
        2
    vinsec  
    OP
       Feb 26, 2020
    @wangsongyan 我测了下 ExecuteTemplate 的第二个参数确切来说应该是模板里的 {{define "form"}} 里的"form",ParseFiles 这里才是模板绝对路径。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1481 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 17:04 · PVG 01:04 · LAX 10:04 · JFK 13:04
    ♥ Do have faith in what you're doing.