javascript easy templates  [ 236 views ]

Goal: build a quick template method

So we have an item template and some values to replace. Do like this way.


  // 1. define the parser
  function template(strings, ...keys) {
    return (function(...values) {
      var dict = values[values.length - 1] || {};
      var result = [strings[0]];
      keys.forEach(function(key, i) {
        var value = Number.isInteger(key) ? values[key] : dict[key];
        result.push(value, strings[i + 1]);
      });
      return result.join('');
    });
  };

  // 2. define the template
  var itemTemplate = template`<li>
      <div class="direction-r">
        <div class="flag-wrapper">
          <span class ="flag">${0}</span>
          <span class ="time-wrapper">${1}</span>
        </div>
        <div class ="desc">${2}</div>
      </div>
    </li>`;

  // 3. use like this

  console.log(itemTemplate('this is the FLAG', ' - time - ', ' - description - '));
  console.log(itemTemplate('second', ' - time 2 - ', ' - description 2 - '));

see also: javascript multiline strings in the code

#sidebar a { color:#fff; } #sidebar ul ul li { color: #DEF585; } #sidebar h2 { color: #fff; } #sidebar ul p, #sidebar ul select { color: #BEDDBE; } #backfly { background: url(images/golfBallWallPaper.jpg) left bottom fixed repeat-x #65a51d; }