I want to include svg files as a html partial so I can use it inline in my HTML. I now I have my svg wrapped in html files and include them like this:
{{ template "/partial/my-svg.html" }}
But I want to include my svg's directly. PHP does this like so:
<?php echo file_get_contents("/partial/my-svg.svg"); ?>
I don't think go has something similar? So I think I need to extend the template logic with a custom function. Something like:
{{ includeSvg "/partial/my-svg.svg" }}
How would such a function look like in go?
Here is a working example of how to add a template function and include an svg by path in a template
package main
import (
"html/template"
"io/ioutil"
"log"
"net/http"
)
func IncludeHTML(path string) template.HTML {
b, err := ioutil.ReadFile(path)
if err != nil {
log.Println("includeHTML - error reading file: %v", err)
return ""
}
return template.HTML(string(b))
}
func main() {
tmpl := template.New("sample")
tmpl.Funcs(template.FuncMap{
"IncludeHTML": IncludeHTML,
})
tmpl, err := tmpl.Parse(`
<!DOCTYPE>
<html>
<body>
<h1>Check out this svg</h1>
{{ IncludeHTML "/path/to/svg" }}
</body>
</html>
`)
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
if err := tmpl.Execute(w, nil); err != nil {
log.Println("Error executing template: %v", err)
}
})
if err := http.ListenAndServe(":8000", nil); err != nil {
log.Fatal(err)
}
}