Export a function to your template.
text/template
은 다른 템플릿 시스템과 마찬가지로 직접 프로그래밍을 시도하지 않습니다. 마크 업으로 데이터 및 기능을 스티치 할 수있는 더 좋은 방법을 제공하며 불충분 한 경우 다른 프리젠 테이션 코드를 작성해야합니다. 사용하는 공통 기능을 추가하기 위해 Funcs()
을 호출하는 New()
버전을 내보내는 yourapp/template
모듈을 작성할 수 있습니다.
(당신은 많은을 위해 단지 이들보다 더 많은 기능 사용을 찾을 수 있습니다, 장고, 예를 들어, 등, 국제화, 서식, 복수화에 대한
lots of builtins 제공을하고, 사람들은 여전히 종종 세트를 확장 할 수 있습니다.)
package main // package mytemplate
import (
"fmt"
"os"
"strings"
"text/template"
)
func conjoin(conj string, items []string) string {
if len(items) == 0 {
return ""
}
if len(items) == 1 {
return items[0]
}
if len(items) == 2 { // "a and b" not "a, and b"
return items[0] + " " + conj + " " + items[1]
}
sep := ", "
pieces := []string{items[0]}
for _, item := range items[1 : len(items)-1] {
pieces = append(pieces, sep, item)
}
pieces = append(pieces, sep, conj, " ", items[len(items)-1])
return strings.Join(pieces, "")
}
// if you use some funcs everywhere have some package export a Template constructor that makes them available, like this:
var commonFuncs = template.FuncMap{
"andlist": func(items []string) string { return conjoin("and", items) },
"orlist": func(items []string) string { return conjoin("or", items) },
}
func New(name string) *template.Template {
return template.New(name).Funcs(commonFuncs)
}
func main() {
// test conjoin
fmt.Println(conjoin("or", []string{}))
fmt.Println(conjoin("or", []string{"Bob"}))
fmt.Println(conjoin("or", []string{"Bob", "Mike"}))
fmt.Println(conjoin("or", []string{"Bob", "Mike", "Harold"}))
people := []string{"Bob", "Mike", "Harold", "Academy Award nominee William H. Macy"}
data := map[string]interface{}{"people": people}
tmpl, err := New("myyy template").Parse("{{ orlist .people }}/{{ andlist .people }}")
if err != nil {
fmt.Println("sadness:", err.Error())
return
}
err = tmpl.Execute(os.Stdout, data)
if err != nil {
fmt.Println("sadness:", err.Error())
return
}
}
Here's a variation 또한 "conjoin"및 "isLast"함수를 내 보냅니다. 마지막 루프에서 다르게 임의의 작업을 수행하는 자세한 구조로 사용할 수 있습니다.
템플릿의 로직을 이동하여 문자열 속성을 통해 노출시키는 것을 고려 했습니까? –
Go 용 다른 템플릿 엔진을 살펴보고 싶을 경우를 대비하여; 나는 pongo2에서이 작업을 어떻게 수행 할 수 있는지에 대한 예를 제시했다. https://www.florian-schlachter.de/pongo2/?id=2077036808 – fls0815
@SimonWhitehead 이것은 확실히 선택 사항이다. 그러나 가능한 경우 템플릿 라이브러리의 제한 사항을 처리하기 위해 "보기/프레젠테이션"코드를 처리하는 코드를 작성하지 않아도됩니다. – Jacob