Skip to content

Instantly share code, notes, and snippets.

@TooManyBees
Created July 11, 2014 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TooManyBees/bcc38a724bcf9bcbcd2c to your computer and use it in GitHub Desktop.
Save TooManyBees/bcc38a724bcf9bcbcd2c to your computer and use it in GitHub Desktop.
roll your own templater?
<div class="entry columns $col_classes bN" data-beacon="{'p':{'mpid':'$i'}}">
<div class="panel">
<a href="clickable" href="$entry_path"></a>
<div class="bN $img_size-img" data-beacon="{'p':{'lnid':'img'}}">
<div class="image-container" data-img-path="$img_path"></div>
</div>
<div class="panel-text">
<h5 class="cf bN" data-beacon="{'p':{'lnid':'hldn'}}">$headline</h5>
</div>
</div>
</div>
<!--
var templ = Template(thatbloboftextupthere);
var output = templ({
i: i,
col_classes: "small-6" || "small-12 large-6",
entry_path: "/us/entry/whatever",
img_size: "large" || "small",
img_path: "http://s.huffingtonpost.com/whatever",
headline: "Barry Odertsky's Empassioned Speech on Accounting Practices"
});
-->
(function() {
function warn(str, key) {
console.warn("Template \""+str.substr(0, 20)+"...\" rendered with missing key: "+key);
}
function exec(str, params) {
params || (params = {});
return str.replace(/\$(\w+)/g, function(match, key) {
if (params[key] === undefined) { warn(str, key); }
return params[key];
});
}
function make(str) {
var trimmed = str.replace(/\s*?\n\s*/gm, ""); // Compress whitespace
return function(params) {
return exec(trimmed, params);
}
}
window.Template = make;
})()
@raphaeleidus
Copy link

(function() {
  function warn(str, key) {
    console.warn("Template \""+str.substr(0, 20)+"...\" rendered with missing key: "+key);
  }

  function exec(str, params) {
    params || (params = {});
    var re;
    for(var key in params) {
      re = new RegExp(key, 'g');
      str.replace(re, params[key]);
    }
    return str.replace(/\$(\w+)/g, function(match, key) {
      if (params[key] === undefined) { warn(str, key); }
      return params[key];
    });
  }

  function make(str) {
    var trimmed = str.replace(/\s*?\n\s*/gm, ""); // Compress whitespace
    return function(params) {
      return exec(trimmed, params);
    }
  }

  window.Template = make;
})()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment