2016-11-16 117 views
0

我想包含svg文件作爲html部分,因此我可以在我的HTML中使用它。 我現在我有我的SVG包裹在HTML文件和包括他們是這樣的:如何直接將SVG作爲html部分包含在Go中

{{ template "/partial/my-svg.html" }} 

但我想直接包括我的SVG的。 PHP這樣做是這樣的:

<?php echo file_get_contents("/partial/my-svg.svg"); ?> 

我不認爲去有類似的東西?所以我想我需要使用自定義函數來擴展模板邏輯。類似於:

{{ includeSvg "/partial/my-svg.svg" }} 

這樣的功能將如何看起來像去?

+1

您正在使用什麼模板引擎添加模板功能,包括SVG工作的例子嗎?默認一個?如果您使用的是默認值,我的建議是將SVG文件讀爲變量並將其傳遞給模板。你可以在這裏找到更多的信息: https://astaxie.gitbooks.io/build-web-application-with-golang/content/en/07.4.html –

+0

你也可以定義一個函數來讀取路徑爲文件並打印內容,[見此](https://golang.org/pkg/text/template/#Template.Funcs)。請注意,您需要將結果包裝到'template.HTML(「string」)'[type](https://golang.org/pkg/html/template/#HTML)以避免html編碼! –

回答

1

下面是如何通過路徑模板

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) 
    } 
} 
相關問題