agolomazov
1/29/2015 - 6:34 PM

Javascript: handlebars.js

/*
 * HANDLEBARS
 */

// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// 1) ПРИМЕР ИСПОЛЬЗОВАНИЯ
// html
<script id="template" type="text/x-handlebars-template">
     <ul class="b10">
          {{#this}}
               <li><a href="/download/{{fileId}}" target="_blank">{{fileTitle}}</a></li>
          {{/this}}
     </ul>
</script>

// json
resData

// js
var source   = $("#").html();
var template = Handlebars.compile(source);
$('.bingo').append(template(resData)); // вставим результат куда нужно


// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// 2) ПРИМЕР ХЭЛПЕРА
// html
<p>{{normalizeDate lastInputDate}}</p>  

// js
Handlebars.registerHelper('normalizeDate', function(lastInputDate) {
    if(lastInputDate) {
       return lastInputDate.substr(0,10);
    } else {
      return '';
    }           
});


// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// 3) Возвращаем HTML код
// js
Handlebars.registerHelper('link', function(object) {
  return new Handlebars.SafeString(
    "<a href='" + object.url + "'>" + object.text + "</a>"
  );
});


// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// 4) IF (если - параметр)
// html
{{#IfCheckThis parametr}}
<p>Один</p>
 {{else}}
<p>Два</p>
 {{/IfCheckThis }}

// js
Handlebars.registerHelper('IfCheckThis ', function(item, block) { // менять нельзя!
	if (item){ // если parametr = true
 		return block.fn(this); // отрисуется "один"
	}
	else{
 		return block.inverse(this); // отрисуется "два"
	}
}); 
 


// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// 5) Выводим пару: ключ - значение
// html
<script id="template" type="text/x-handlebars-template">
    {{#eachkeys data}}
    <li>{{this.key}} - {{this.value}}</li>
    {{/eachkeys}}
</script>
<div id="content">
</div>

// js
Handlebars.registerHelper('eachkeys', function(context, options) {
  var fn = options.fn, inverse = options.inverse;
  var ret = "";

  var empty = true;
  for (key in context) { empty = false; break; }

  if (!empty) {
    for (key in context) {
        ret = ret + fn({ 'key': key, 'value': context[key]});
    }
  } else {
    ret = inverse(this);
  }
  return ret;
});

$(function() {
    var data = {"interval":"2012-01-21",
      "advertiser":"Advertisers 1",
      "offer":"Life Insurance",
      "cost_type":"CPA",
      "revenue_type":"CPA"};
                
    var source   = $("#template").html();
    var template = Handlebars.compile(source);
    $('#content').html(template({'data': data}));
});

// result
// interval - 2012-01-21
// advertiser - Advertisers 1
// offer - Life Insurance
// cost_type - CPA
// revenue_type - CPA



// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// 6) Первый элемент массива в шаблоне
// json
{
  people: [
    {"name":"Yehuda Katz"},
    {"name":"Luke"},
    {"name":"Naomi"}
  ]
}

// html
<ul id="luke_should_be_here">
{{people.1.name}}
</ul>



// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// 7) Комментарии
{{! комментарии тут }}



// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// 8) Как вставлять html из json
// json
{ body: "<p>This is a post about &lt;p&gt; tags</p>"}
// html
{{{body}}}



// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// 9) With
// Мы можем смещать контектст конкретной секции шаблона
// html
<div class="entry">
  <h1>{{title}}</h1>
  {{#with author}}
  <h2>By {{firstName}} {{lastName}}</h2>
  {{/with}}
</div>

// JSON
{
  title: "My first post!",
  author: {
    firstName: "Charles",
    lastName: "Jolley"
  }
}

// Результат:
<div class="entry">
  <h1>My first post!</h1>
  <h2>By Charles Jolley</h2>
</div>



// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// 10) each
// html
<ul class="people_list">
  {{#each people}}
  <li>{{this}}</li>
  {{/each}}
</ul>

// JSON
{
  people: [
    "Yehuda Katz",
    "Alan Johnson",
    "Charles Jolley"
  ]
}

// RESULT
<ul class="people_list">
  <li>Yehuda Katz</li>
  <li>Alan Johnson</li>
  <li>Charles Jolley</li>
</ul>



// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// 11) IF
<div class="entry">
  {{#if author}}
    <h1>{{firstName}} {{lastName}}</h1>
  {{else}}
    <h1>Unknown Author</h1>
  {{/if}}
</div>



// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// 12) unless - противоположность IF
<div class="entry">
  {{#unless license}}
  <h3 class="warning">WARNING: This entry does not have a license!</h3>
  {{/unless}}
</div>



// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// 13) Пути
// Перемещаться можно как по JSON:
author.name - глубже
../ - вернутся в родительскую область (можно и глубже ../../../)



// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// 14) *связка хэлпера с each this 
// html
<ul>
  {{#each items}}
  <li>{{agree_button}}</li>
  {{/each}}
</ul>

// JSON
var context = {  items: [
    {name: "Handlebars", emotion: "love"},
    {name: "Mustache", emotion: "enjoy"},
    {name: "Ember", emotion: "want to learn"}  ]};

// JAVASCRIPT
Handlebars.registerHelper('agree_button', function() {
  return new Handlebars.SafeString(
    "<button>I agree. I " + this.emotion + " " + this.name + "</button>"
  );
});

// РЕЗУЛЬТАТ
<ul>
  <li><button>I agree. I love Handlebars</button></li>
  <li><button>I agree. I enjoy Mustache</button></li>
  <li><button>I agree. I want to learn Ember</button></li>
</ul>