2012-03-31 7 views
7

여기 앱의 Example입니다.Golang GAE - 콧수염 구조체의 intID

Google Appengine의 Golang에 약간의 블로그 시스템을 구축하고 Mustache를 템플릿 엔진으로 사용하려고 시도 중입니다. 필수 코드는 다음 위치에 있습니다 : golang-code/handler/handler.go 그래서, GAE 자동 intID (INT64)를 할당

datastore.Put(c, datastore.NewIncompleteKey(c, "Blogposts", nil), &blogposts) 

통해

type Blogposts struct { 
    PostTitle string 
    PostPreview string 
    Content  string 
    Creator  string 
    Date  time.Time 
} 

데이터는 GAE에 전달된다

은 그래서, 구조체를 갖는다. 는 이제 최신 블로그 게시물

// Get the latest blogposts 
c := appengine.NewContext(r) 
q := datastore.NewQuery("Blogposts").Order("-Date").Limit(10) 

var blogposts []Blogposts 
_, err := q.GetAll(c, &blogposts) 

모든 것이 잘가 작동 할 때까지

을 얻기 위해 노력했다,하지만 난 intID에 액세스하려고 할 때 (또는 stringID를, 무엇이든) 나는이 :-(

<h3><a href="/blog/read/{{{intID}}}">{{{PostTitle}}}</a></h3> 
에 대한 액세스를 필요 없다 ?

(PostTitle이 intID, 나는 사물의 수천을 해봤하지, 작품, 아무것도 :-(일하지)

누구나 생각이 좋은 것

편집 :! 나는 콧수염을 사용합니다. 코드에서

http://mustache.github.com/

내가 사용
x["Blogposts"] = blogposts 
data := mustache.RenderFile("templates/about.mustache", x) 
sendData(w, data) // Equivalent to fmt.Fprintf 

그리고 데이터와 .mustache 템플릿에 액세스 할 수 있습니다

{{{내용}}} 또는 {{{PostTitle}}}

+0

'{{{}}}': html/템플릿을 확장하고 있습니까? 그렇다면 최소한 코드 조각을 추가하여 살펴보십시오. – zzzz

+0

안녕하세요, 아니요, 저는 콧수염을 사용합니다. 편집을 참조하십시오 :-) – Testuser

답변

8

intID은 구조체가 아닌 키의 내부 속성이며 다음을 통해 액세스 할 수 있습니다. 게터 :

id := key.IntID() 

GetAll 반환 []*Key, 사용하지 않는 :

_, err := q.GetAll(c, &blogposts) 

한 가지 방법은이 문제를 얻으려면이 검증되지 않은 게시물 및 키 정보를 모두 가지고있는 뷰 모델 구조체를 (만드는 것입니다 , 그러나 이것은 그것의 요지입니다) :

//... handler code ... 

    keys, err := q.GetAll(c, &blogposts) 
    if err != nil { 
    http.Error(w, "Problem fetching posts.", http.StatusInternalServerError) 
    return 
    } 

    models := make([]BlogPostVM, len(blogposts)) 
    for i := 0; i < len(blogposts); i++ { 
    models[i].Id = keys[i].IntID() 
    models[i].Title = blogposts[i].Title 
    models[i].Content = blogposts[i].Content 
    } 

    //... render with mustache ... 
} 

type BlogPostVM struct { 
    Id int 
    Title string 
    Content string 
} 
+0

대단히 고마워요, 제게 많은 도움이되었습니다! :-) – Testuser

0

AFAICS, Blogposts 구조체에는 intID 필드가 없지만 필드에는 PostTitle이 있습니다. 나는 그것이 콧수염을 사용한 적이 없지만 그 이유는 앞뒤가 맞지 않는 이유가 될 수 있다고 생각합니다 ...

+0

그건 부적당합니다. 데이터 저장소는 "intID"와 "stringID"를 무시합니다 .-- (NewIncompleteKey를 통해 intID를 지정하려고하면 작동하지 않습니다 ;-)) – Testuser

+0

'data : = mustache.RenderFile ("templates/about.mustache ", x)', Datastore에 대한 정보가 아닙니다. 'RenderFile' 함수는'intID'를 어떻게 알 수 있습니까? – zzzz

+0

응답 해 주셔서 감사합니다. 그리고 나쁜 영어로 미안해. (어쩌면 무례한 소리가 들리 겠지만 내 의도는 그렇지 않다!) x는 Blogposts 구조체 (및 다른 것들)를 포함하고있다. 내가 intid를 Blogposts 구조체에 추가하려고하면 IMHO를 사용할 수 없기 때문에 작동하지 않습니다. struct :-( – Testuser

15

hyperslug가 지적했듯이 엔티티의 id 필드는 키에 있고 읽을 수있는 구조체가 아닙니다.그래서

같은)

type Blogposts struct { 
    PostTitle string 
    PostPreview string 
    Content  string 
    Creator  string 
    Date  time.Time 
    Id   int64 `datastore:"-"` 
} 

당신은 수동 GETALL를 호출 (후 ID 필드를 채울 수 있습니다 :이 약

또 다른 방법은 구조체에 id 필드를 추가하고 ignore it에 데이터 저장소를 말해, 예를 들어하는 것입니다

keys, err := q.GetAll(c, &blogposts) 
if err != nil { 
    // handle the error 
    return 
} 
for i, key := range keys { 
    blogposts[i].Id = key.IntID() 
} 

추가 유형을 도입하지 않는 이점이 있습니다.

2

나는이 문제가 몇 년 전임을 알고 있지만, 다음 기사는이 점에 관해서 나에게 매우 도움이되었다 : Golang basics with Google Datastore. 기사에

은, 저자는

func GetCategory(c appengine.Context, id int64) (*Category, error) { 
    var category Category 
    category.Id = id 

    k := category.key(c) 
    err := datastore.Get(c, k, &category) 
    if err != nil { 
    return nil, err 
    } 

    category.Id = k.IntID() 

    return &category, nil 
} 

...뿐만 아니라 목록/수집을 받고 ... 당신의 ID로 엔티티를 가져 쿼리를 실행할 수있는 방법의 좋은 예를 제공합니다 관련 ID를 가진 엔티티 :

func GetCategories(c appengine.Context) ([]Category, error) { 
    q := datastore.NewQuery("Category").Order("Name") 

    var categories []Category 
    keys, err := q.GetAll(c, &categories) 
    if err != nil { 
    return nil, err 
    } 

    // you'll see this a lot because instances 
    // do not have this by default 
    for i := 0; i < len(categories); i++ { 
    categories[i].Id = keys[i].IntID() 
    } 

    return categories, nil 
} 

위의 스 니펫은 @koz의 유용한 답변과 매우 유사합니다.