2012-07-02 1 views
10

나는 아래이부분적으로 밑줄이있는 템플릿 (핸들 바처럼)?

var PeopleModel = Backbone.Model.extend({ 
defaults: {    
    "people": [ 
      { "username": "alan", "firstName": "Alan", "lastName": "Johnson", "phone": "1111", "email": "[email protected]" }, 
      { "username": "allison", firstName: "Allison", "lastName": "House", "phone": "2222", "email": "[email protected]" }, 
      { "username": "ryan", "firstName": "Ryan", "lastName": "Carson", "phone": "3333", "email": "[email protected]" }, 
      { "username": "ed", "firstName": "Edward", "lastName": "Feild", "phone": "4444", "email": "[email protected]" }, 
      { "username": "phil", "firstName": "Philip", "lastName": "Doom", "phone": "5555", "email": "[email protected]" }, 
      { "username": "gerald", "firstName": "Gerald", "lastName": "Butler", "phone": "6666", "email": "[email protected]" } 
    ], 
    "company": {"name": "Random Corp."}, 
    "country": "England" 
} 

}); 

와 같은 백본 모델

<script id="people-template" type="text/x-handlebars-template"> 
{{#each people}} 
    {{> person}} 
{{/each}} 
</script> 

<script id="person-partial" type="text/x-handlebars-template"> 
<div class="person"> 
    <h2>{{fullName}} </h2> 
    <div class="phone">{{phone}}</div> 
    <div class="email"><a href="mailto:{{email}}">{{email}}</a></div>  
</div> 

이 나는 ​​부분 사용 handlebars.js을 구현하는 방법을 내 템플릿입니다 있습니다.

내 질문에

1.Do 우리는 비슷한 일이, 내가 넣다 underscore.js 템플릿 엔진의 파셜 뜻? 우리가 underscore.js 템플릿 엔진

답변

16

아니, 밑줄의 템플릿에는 기본 부분적인 지원이없는에서 부분적인 구현 어떻게 그렇게

2.If. 그러나, 원하는 JavaScript를 꽤 많이 넣을 수 있습니다. <% ... %>; 특히, 자신 만의 함수를 호출 할 수 있기 때문에, 어려움없이 partial-ish를 추가 할 수 있습니다. 당신은이 같은 템플릿 수 :

<script id="people-template" type="text/x-handlebars-template"> 
    <% _(people).each(function(person) { %> 
     <%= partial('person', person) %> 
    <% }) %> 
</script> 

을 다음 partial 기능 window에 추가

window.partial = function(which, data) { 
    var tmpl = $('#' + which + '-partial').html(); 
    return _.template(tmpl)(data); 
}; 

데모 : http://jsfiddle.net/ambiguous/HDuj5/9/

꽤 매끄러운 아니다 및 핸들 바에서 꽤 같은 {{> ... }}하지만, Underscore의 템플릿은 JavaScript 자체를 감싸는 매우 얇은 래퍼이며 사용자를 어느 정도 제한합니다. 네임 스페이스를 사용하여 직접 window에 넣지 않거나 {variable: ...} option to _.template 및 래퍼를 사용하여 표준 도우미를 설정할 수 있습니다.

+0

감사합니다, 당신의 바이올린은 많은 도움이되었습니다. 나는이 경우 "창"사용에 대해 완전히 잊었다. 다시 한번 – bhargav

+1

데이터를 두 번째 인수로 갖는'_.template()'의 두 인자 버전이 1.7 버전에서 삭제되었다는 것에주의하십시오. 그러나 접근법은 여전히 ​​건전합니다. –

+0

@ PeterV.Mørch : 알림을 보내 주셔서 감사합니다. 나는 실제로 "_template (tmpl, data)'가 왜 작동하지 않는지에 대해 대답했다." 최근 질문. –

13

또는 당신과 같이 서식 도우미에 혼합 할 수 전역 범위의 사용을 피하는 :

(function() { 
    var originalUnderscoreTemplateFunction = _.template; 
    var templateHelpers = {}; 

    _.mixin({ 
     addTemplateHelpers : function(newHelpers) { 
      _.extend(templateHelpers, newHelpers); 
     }, 

     template : function(text, data, settings) { 
      // replace the built in _.template function with one that supports the addTemplateHelpers 
      // function above. Basically the combo of the addTemplateHelpers function and this new 
      // template function allows us to mix in global "helpers" to the data objects passed 
      // to all our templates when they render. This replacement template function just wraps 
      // the original _.template function, so it sould be pretty break-resistent moving forward. 

      if(data) 
      { 
       // if data is supplied, the original _.template function just returns the raw value of the 
       // render function (the final rentered html/text). So in this case we just extend 
       // the data param with our templateHelpers and return raw value as well. 

       _.defaults(data, templateHelpers); // extend data with our helper functions 
       return originalUnderscoreTemplateFunction.apply(this, arguments); // pass the buck to the original _.template function 
      } 

      var template = originalUnderscoreTemplateFunction.apply(this, arguments); 

      var wrappedTemplate = function(data) { 
       _.defaults(data, templateHelpers); 
       return template.apply(this, arguments); 
      }; 

      return wrappedTemplate; 
     } 
    } 
} 

여기에

_.addTemplateHelpers({ 
    partial : function() { 
     return _.template(
      $('#' + which + '-partial').html(), 
      data 
     ); 
    } 
}); 

전화 GitHub의에 underscore mixin에 대한 링크입니다.

+0

이것을 달성하기 위해 _.partial 및 _.template으로 무엇인가 할 수 있습니까? – backdesk

+0

_partial은 템플릿 부분과 관련이 없습니다. 함수의 인수를 채 웁니다. – Dtipson

1

나는이 데이브의 대답과 유사하다 생각하지만, 아마도 적은 코드를 필요로 :

function partialTemplate(origTemplate, partialValues){ 
    return function(values){ 
     return origTemplate(_.defaults(values, partialValues)); 
    }; 
} 

사용 예제 : 참을성 내 질문에 대답하기위한

var t = _.template('<%= val1 %>,<%= val2 %>'); // original template requiring 2 values 
var pt = partialTemplate(t, {val1:1}); // partial template with 1 value pre-populated 
pt({val2:2}); // returns '1,2' 
pt({val2:3}); // returns '1,3'