2014-11-12 5 views
1

그것은 이미 다른 곳에서 당신은 쉼표로 구분 된 목록을 인쇄 할 수 있습니다 유래에 설명 쉼표로 분리 "또는" 당신은 "또는"포함하는 마지막 항목에 대한 다른 목록 구분이 필요합니다사용 golang 템플릿,

{name}, {name}, {name}, or {name} 

이 예를 들어, 수 있도록하는 것입니다, 같은 형식의 문장의 생성 :

The members of this team are Bob, Jane, and Mike. 

운동 할 수있는 템플릿 코드는 매우 복잡하고 복잡합니다.

+0

템플릿의 로직을 이동하여 문자열 속성을 통해 노출시키는 것을 고려 했습니까? –

+1

Go 용 다른 템플릿 엔진을 살펴보고 싶을 경우를 대비하여; 나는 pongo2에서이 작업을 어떻게 수행 할 수 있는지에 대한 예를 제시했다. https://www.florian-schlachter.de/pongo2/?id=2077036808 – fls0815

+0

@SimonWhitehead 이것은 확실히 선택 사항이다. 그러나 가능한 경우 템플릿 라이브러리의 제한 사항을 처리하기 위해 "보기/프레젠테이션"코드를 처리하는 코드를 작성하지 않아도됩니다. – Jacob

답변

3

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"함수를 내 보냅니다. 마지막 루프에서 다르게 임의의 작업을 수행하는 자세한 구조로 사용할 수 있습니다.

2

목록에서 "적절한 영어 형식화 된 문장 만들기"기능을 사용하십시오.

귀하의 복수의 예는 하나 개의 요소가 목록에있는 곳에 당신의 유일한 예는 무엇인가

 
The members of this team are Bob, Jane, and Mike. 

입니까? 예 :

 
The only member of this team is Bob. 

목록에 요소가없는 경우의 빈 예제는 무엇입니까? 예 :

 
There are no members of this team. 

편지 병합에서 적절한 영어 문장과 단락을 만드는 것은 어렵습니다.

+0

제발 영어로 끊지 마세요. 내 질문은 마지막 항목에있는 "또는"쉼표로 구분 된 목록을 생성하는 방법에 대한 것입니다. – Jacob

+0

나는 그가 질문에 대답했다고 생각한다. 함수를 사용하십시오. – twotwotwo