0

밑줄 템플릿과 Backbone.js를 사용하여 데이터의 JS 개체를 렌더링하려고합니다.밑줄 템플릿을 사용하여 JS 객체를 렌더링하는 방법은 무엇입니까?

아래 그림과 같은 데이터를 생성했습니다.

JS object data

후, 나는 비슷한 질문을 보았다.
How to display a JS object with underscore templates?

나는 Backbone.js 컬렉션 및 모델을 정확하게 알지 못했지만 최근에는 그 사실을 이해했습니다.
나는 아래 소스 코드와 같은 컬렉션을 삽입하는 데이터를 만들었습니다.

//that's create view 
wordCollection.add(wordList); 
var view = new views.Livingword({collection:wordList}); 

//that's view 
render: function(templateName) { 
     var template = _.template(templateName); 
     this.$el.html(template({result : this.collection.category})); 
     return this; 
     } 

다음으로 html 소스 코드를 작성했습니다.

<% _.each(result, function(item,key,list){ %> 
      <tr> 
      <td><%- category[key].bedroom %></td> 
      </tr> 
      <% }) %> 

하지만, 오류가 Uncaught ReferenceError: category is not defined
인쇄됩니다 그래서 내가 console.log(this.collection.category);이 사진 아래에 실행할 때 콘솔 명령의 결과 collection을 디버깅하려고합니다. this.collection.category result

데이터를 만드는 것이 적절하고 잘못된 소스 코드를 찾지 못한다고 생각합니다.
내 데이터를 html로 렌더링하려면 어떻게해야합니까?

+2

당신은 템플릿'this.collection.category'로'result' 전달됩니다
그래서 모든 변경 사항과 코드가 뭔가 템플릿으로

template: _.template(templateName), // one time render: function(templateName) { this.$el.html(this.template({categories: this.model.categories}); // ---- This can be an Array or Collection instance -----^ return this; } 

처럼이어야합니다. 그러므로'category [key] ..'대신'result [key] ..'를 사용해야합니다. 템플릿 범위에서'category'는'undefined'가되어야합니다. – RaR

+0

오 세상에 .. 정말 고마워요 –

+0

@RaR 흠 .. 오류는 처리되지만 아무 것도 표시되지 않습니다 ..'%% result [key] .audioSrc %>' 뭐가 문제 야? –

답변

2

각 반복에서 코드에있는 item은 객체를 포함하는 배열 인 "침실"과 같은 항목의 값입니다.
그래서 내부의 각 항목을 인쇄하려면 다른 반복이 필요합니다.

<% _.each(result, function(arr, key, list){ %> 
<!-- Add <tbody>, <thead> etc with "key" here --> 

    <% _.each(arr, function(item, key, list){ %> 
    <tr> 
     <td><%= item.audioSrc %></td> 
    </tr> 
    <% }) %> 

<% }) %> 

위의 코드에서 audioSrc은 하드 코드되어 있습니다. 인쇄하려는 모든 속성을 알고 있다면 그렇게 할 수 있습니다. 동적이지 않은 경우 항목의 각 속성을 수행하려면 다른 반복이 필요합니다.

사이드 노트 : 대신 모든 렌더링에 var template = _.template(templateName);을 실행

  • template: _.template(templateName), // one time 
    render: function(templateName) { 
        this.$el.html(this.template({result: this.collection.category})); 
        return this; 
    } 
    
  • 당신이 템플릿에 통과 것들에 의미있는 이름을 부여 할. result은 모호한 이름입니다. category이 더 좋지만 카테고리 맵이므로 올바른 이름은 categories입니다. 따라서 this.template({categories: this.collection.category}. 이름이 명확하다면 템플릿을 작성하는 동안 수행중인 작업에 대해 더 잘 이해할 수 있습니다.

  • 사용법에 따라 : this.collection.category, 저는 모델이어야하며 컬렉션이 아니어야합니다. 컬렉션은 사물의 그룹을위한 것이며 당신은 this.collection.models과 같은 모델 배열을 사용할 것입니다.

    <% _.each(categories, function(category, name){ %> 
    <!-- Add <tbody>, <thead> etc with "name" here --> 
    
        <% _.each(category, function(item, name){ %> 
        <tr> 
         <td><%= item.audioSrc %></td> 
        </tr> 
        <% }) %> 
    
    <% }) %> 
    
+0

위대한 !! 정말 고맙습니다 :) –