Подтвердить что ты не робот

Шаблон Partials в подчеркивании (как и в руле)?

У меня есть базовая модель, подобная этой

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. У нас есть аналогичная вещь, я имею в виду частичное включение шаблона шаблона underscore.js?

2. Если так, как мы реализуем частичное в шаблоне шаблона underscore.js

4b9b3361

Ответ 1

Нет, в шаблонах Underscore нет частичной частичной поддержки. Но вы можете разместить практически любой JavaScript, который вы хотите внутри <% ... %>; в частности, вы можете назвать свои собственные функции, чтобы вы могли добавить что-то частично-иш без особых трудностей. У вас может быть такой шаблон:

<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/

Это не совсем так гладко и красиво, как {{> ... }} в Handlebars, но шаблоны Underscore - очень тонкая оболочка вокруг самого JavaScript, и это немного ограничивает вас. Вы можете использовать пространства имен, чтобы не помещать вещи непосредственно в window, или вы могли бы использовать параметр {variable: ...} для _.template и обертка для установки ваши стандартные помощники.

Ответ 2

Или, чтобы избежать использования глобальной области, вы можете смешивать в глобальных помощниках шаблонов, например:

(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
        );
    }
} );

Вот ссылка на подчеркивание mixin на github.

Ответ 3

Я думаю, что это похоже на ответ Дэйва, но, возможно, требуется меньше кода:

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'