Golang : How to call function inside template with template.FuncMap
Alright, just a simple tutorial on how to call your own function inside HTML template. For this example, we will "import" the WordWrap function into the template using the template.FuncMap()
and call it from inside a template.
Here you go!
package main
import (
"fmt"
"os"
"strings"
"text/template"
)
const TextData = `After wordwrap :
{{(wordwrap .Message 3) }}` // change 3 to 2 or 1 and see how it goes
var templateDataMap = map[string]interface{}{}
func main() {
templateDataMap["Message"] = "this is a simple message string"
var ownFuncs = template.FuncMap{"wordwrap": WordWrap}
var PageBody = template.Must(template.New("PageBody").Funcs(ownFuncs).Parse(TextData))
if err := PageBody.ExecuteTemplate(os.Stdout, "PageBody", templateDataMap); err != nil { // replace os.Stdout with w http.ResponseWriter for html/template
fmt.Println(err)
}
}
func WordWrap(s string, limit int) string {
if strings.TrimSpace(s) == "" {
return s
}
// convert string to slice
strSlice := strings.Fields(s)
var result string = ""
for len(strSlice) >= 1 {
// convert slice/array back to string
// but insert \r\n at specified limit
result = result + strings.Join(strSlice[:limit], " ") + "\r\n"
//result = result + strings.Join(strSlice[:limit], " ") + "<br>" this is for HTML
// discard the elements that were copied over to result
strSlice = strSlice[limit:]
// change the limit
// to cater for the last few words in
//
if len(strSlice) < limit {
limit = len(strSlice)
}
}
return result
}
Sample output:
this is
a simple
message string
References:
https://www.socketloop.com/references/golang-html-template-funcmap-type-examples
https://www.socketloop.com/tutorials/golang-populate-dropdown-with-html-template-example
See also : Golang : Auto-generate reply email with text/template package
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+21.4k Golang : Convert string slice to struct and access with reflect example
+5.7k Golang : Use NLP to get sentences for each paragraph example
+15.4k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy
+9k Golang : Generate random Chinese, Japanese, Korean and other runes
+4.7k JQuery : Calling a function inside Jquery(document) block
+7.7k Swift : Convert (cast) String to Float
+14.9k Golang : Get all local users and print out their home directory, description and group id
+5.1k PHP : Hide PHP version information from curl
+9.2k Golang : How to extract video or image files from html source code
+11k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+6.1k Golang : Selection sort example
+8.9k Golang : Create and shuffle deck of cards example