Handlebars Renderer

Simple each loop with @index being used.

by Ben Clayton

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.js"></script>
<div class="thepeople"></div>

<script id="person" type="text/html">
  {{#each tags}}
  <div class="contact">
    <div data-mydata={{data}}>{{@index}} {{name}}</div>
  </div>
  {{/each}}

</script>

<br><br>
Note: You cannot set actual data in a data attribute on an element, only puts in a string

CSS

.thepeople {
  margin-top: 30px;
  position: relative;
}

.contact {
  position: relative;
  border: 1px solid red;
  width: 200px;
  padding: 5px;
  margin: 4px;
  background-color: #FFFFD0;
  opacity: 1;
  overflow: hidden;
}

.small {
  font-size: 12px;
}

JavaScript

var data = {
  tags: [{
      name: "tag value zero",
			data: [1,2]
    },{
      name: "tag value one"
    },{
      name: "tag value two"
    },{
      name: "tag value three"
    },{
      name: "tag value four"
    },{
      name: "tag value five"
    },{
      name: "tag value six"
    },{
      name: "tag value seven"
    },{
      name: "tag value eight"
    },{
      name: "tag value nine"
    },{
      name: "tag value ten"
    },
  ]
};

Handlebars.registerHelper('compare', function(value1, comparator, value2, options) {

  var match;
  debugger;

  switch (comparator) {
    case "==":
      match = (value1 == value2);
      break;

    case "===":
      match = (value1 === value2);
      break;

    case "!=":
      match = (value1 != value2);
      break;

    case ">":
      match = (value1 > value2);
      break;

    case "<":
      match = (value1 < value2);
      break;

    case ">=":
      match = (value1 >= value2);
      break;

    case "<=":
      match = (value1 <= value2);
      break;

    case ">=":
      match = (value1 >= value2);
      break;

    case "eq":
      match = (value1.toString() == value2.toString());
      break;

    case "ne":
      match = (value1.toString() != value2.toString());
      break;

    case "=~":
    case "regex":
    case "match":
      var re = new RegExp(value2, 'i');
      var m = re.exec(value1);
      match = (m && (m.length > 0));
      break;


    default:
      match = false;
      console.error("Handlebars Helper - Compare was not given a supported operator");
  }

  if (match) {
    return options.fn(this);
  } else {
    return options.inverse(this);
  }

});


function render() {

  var source = $("#person").html();
  var template = Handlebars.compile(source);
  $('.thepeople').html(template(data));
}


render();