I can't send a function to template when I use another file instead of main.go
my problem is in Second Part.
First Part: (first part works fine.)
I can send a function->"humanSize" to the template->"temp.gohtml"
this is my directory:
app
|____main.go
|____templates
|_____index
|_____temp.gohtml
when I write a code like blow it works fine:
import (
"html/template"
"log"
"net/http"
"os"
)
var funcMap = template.FuncMap{
"humanSize": humanSize,
}
var tpl *template.Template
func init() {
tpl = template.Must(template.New("").Funcs(funcMap).ParseFiles("templates/index/temp.gohtml"))
}
func humanSize() string {
return "qqqqqqqqqqqqqqqqqqqqq"
}
func getPageHandler(w http.ResponseWriter, r *http.Request) {
err := tpl.ExecuteTemplate(os.Stdout,"temp.gohtml", nil)
if err != nil {
log.Fatalln(err)
}
}
func main() {
http.HandleFunc("/", getPageHandler)
http.ListenAndServe(":8082", nil)
}
this is a code of templates/index/temp.gohmtl :
<html>
<body>
{{humanSize}}
</body>
</html>
output is ok:
<html>
<body>
qqqqqqqqqqqqqqqqqqqqq
</body>
</html>
Second Part: (I have a problem here.)
I want to move the code from main.go to controller/index.go
this is my new directory:
app
|____main.go
|____templates
| |_____index
| |_____temp.gohtml
|____controller
|_____index.go
|_____login.go
//Answer: I edited this line just for another person wants to know what was the problem...I have imported some files in login.go same as index.go that cause "relative imports" and I got the error. in index.go also we have "relative imports" with config.go
I write a code in main.go :
import (
Con "./controller"
"net/http"
)
func main() {
http.HandleFunc("/", Con.GetPageHandler)
http.ListenAndServe(":8082", nil)
}
and I write a code in controller/index.go :
package controller
import (
"html/template"
"log"
"net/http"
"os"
)
var funcMap = template.FuncMap{
"humanSize": humanSize,
}
var tpl *template.Template
func init() {
tpl = template.Must(template.New("").Funcs(funcMap).ParseFiles("templates/index/temp.gohtml"))
}
func humanSize() string {
return "qqqqqqqqqqqqqqqqqqqqq"
}
func GetPageHandler(w http.ResponseWriter, r *http.Request) {
err := tpl.ExecuteTemplate(os.Stdout,"temp.gohtml", nil)
if err != nil {
log.Fatalln(err)
}
}
Error:
2019/04/12 21:44:49 template: temp.gohtml:11: function "humanSize" not defined
summary: when I write a code in main.go I can send a function to template but when I a code in controller/index.go I can't send a function to template.