2017-01-08 10 views
0

가능한 한 간단하게 만들려고합니다. Golang에는 템플릿 파일로 구문 분석되는 두 개의 변수가 있습니다. 던져 패닉과 함께 bad character U+0024 '$' : 내 HTML 파일에서 다음골란 템플릿 - 범위 변수 내에서 전역 변수로 템플릿 변수 사용

for _, issue := range issues { 
    issueIDStr := strconv.Itoa(*issue.ID) 
    parse[*issue.ID] = issueIDStr 
    parse[issueIDStr+"-label"] = "blah blah" 
} 

:

{{ range .issues }} 
    <!-- Here I want to use the current issue's ID as a global variable which is outside the range loop --> 
    <!-- According to the Golang doc which says the following: 
      When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot. 
     I can use $.Something to access a variable outside my range loop right... 
     but how can I use a template variable as a global variable? I tried the following which doesn't work. 
    {{ $ID := .ID }} 
    <p>{{ index $.$ID "author" }}</p> 
{{ end }} 

이 코드를 실행 한 후, 나는 오류가 여기에

는 변수를 선언하는 내 Golang 코드 .

내가 현재 완전히 시도 할 수없는 것은 무엇입니까, 아니면 내가 놓친 트릭이 있습니까?

감사합니다 :)

+0

당신은 $ $의 ID처럼 사용할 수는, 그것이 예상대로 평가 wount

다음은 위의 제안을 보여주는 확장 된 예제 . 다르게 배열해야 할 수도 있습니다. –

+0

글로벌지도를 사용하고 키로 ID를 사용하십시오. –

+0

@Acidic, 템플릿 실행 방법 (...)을 나타내는 코드 줄을 추가하십시오. –

답변

0

당신은 단순히 문제의 배열을 포함하는지도 [문자열] 인터페이스를 {}해야 한 다음 사용하는 템플릿 실행 데이터로.

그런 다음 문제를 반복하고 템플릿에서 해당 멤버에 직접 액세스 할 수 있습니다. 당신이 원하는 또한 경우

issue: 1 
     author: Pepe 

issue: 2 
     author: Cholo 

을/당신이 "부자"문제를 정의해야 템플릿 렌더링 프로세스에 특정 데이터를 추가해야합니다

const t = ` 
{{ range .issues }} 
issue: {{ .ID }} 
    author: {{ .Author }} 
{{ end }} 
` 

type Issue struct { 
    ID  int 
    Author string 
} 

func main() { 
    issues := []Issue{{1, "Pepe"}, {2, "Cholo"}} 
    data := map[string]interface{}{"issues": issues} 
    tpl := template.Must(template.New("bla").Parse(t)) 
    tpl.Execute(os.Stdout, data) 
} 

출력 : 여기에

작은 완벽한 예제 이 목적을 위해 구조체를 만들고 템플릿을 템플릿 실행에 전달하기 전에 모델을 변환하십시오. 이는 정적으로 알려진 추가 데이터 (RichIssue의 단순 멤버)와 동적으로로드 된 데이터 (맵의 키/값) 모두에 대해 수행 할 수 있습니다. . 다음과 같은 출력을 생성

const t = ` 
{{ range .issues }} 
issue: {{ .ID }} 
    author: {{ .Author }} 
    static1: {{ .Static1 }} 
    dyn1: {{ .Data.dyn1 }} 
{{ end }} 
` 

type Issue struct { 
    ID  int 
    Author string 
} 

type RichIssue struct { 
    Issue 
    Static1 string     // some statically known additional data for rendering 
    Data map[string]interface{} // container for dynamic data (if needed) 
} 

func GetIssueStatic1(i Issue) string { 
    return strconv.Itoa(i.ID) + i.Author // whatever 
} 

func GetIssueDyn1(i Issue) string { 
    return strconv.Itoa(len(i.Author)) // whatever 
} 

func EnrichIssue(issue Issue) RichIssue { 
    return RichIssue{ 
     Issue: issue, 
     Static1: GetIssueStatic1(issue), 
     // in this contrived example I build "dynamic" members from static 
     // hardcoded strings but these fields (names and data) should come from 
     // some kind of configuration or query result to be actually dynamic 
     // (and justify being set in a map instead of being simple static 
     // members as Static1) 
     Data: map[string]interface{}{ 
      "dyn1": GetIssueDyn1(issue), 
      "dyn2": 2, 
      "dyn3": "blabla", 
     }, 
    } 
} 

func EnrichIssues(issues []Issue) []RichIssue { 
    r := make([]RichIssue, len(issues)) 
    for i, issue := range issues { 
     r[i] = EnrichIssue(issue) 
    } 
    return r 
} 

func main() { 
    issues := []Issue{{1, "Pepe"}, {2, "Cholo"}} 
    data := map[string]interface{}{"issues": EnrichIssues(issues)} 
    tpl := template.Must(template.New("bla").Parse(t)) 
    tpl.Execute(os.Stdout, data) 
} 

:

issue: 1 
    author: Pepe 
    static1: 1Pepe 
    dyn1: 4 

issue: 2 
    author: Cholo 
    static1: 2Cholo 
    dyn1: 5 
+0

예.이 작업을 수행했지만 문제는 [] 문제의 각 문제에 데이터를 추가해야하지만 문제 유형을 변경할 수 없습니다. 예를 들어, issue.author = "Pepe"가 있습니다. 문제가 발생할 때마다 새로운 정보를 추가해야한다면 어떻게해야할까요? – Acidic

+0

정적으로 알려진 데이터를 각 항목에 추가해야하는 경우 (문제) 가장 관용적이며 직관적 인 방법은 템플릿에 표시하려는 모든 데이터를 포함 할 수있는 새로운 문제 구조체, 즉 "RichIssue"를 간단히 정의하는 것입니다. [] 문제를 [] RichIssue로 변환하고 그 결과를 사용하여 템플릿에 대해 템플릿을 실행합니다. –

+0

동적 데이터를 추가해야하는 경우 RichIssue에 map [string] interface {} 멤버를 추가해야합니다. 그러면 RichIssue로 이슈를 변형 할 때 추가 데이터를 해당 멤버에 추가 할 수 있습니다 (모든 정적으로 알려진이 문제를 피하려고합니다. 노출 될 데이터). –