Skip to content

Instantly share code, notes, and snippets.

@sillero
Created November 14, 2012 19:06
Show Gist options
  • Save sillero/4074062 to your computer and use it in GitHub Desktop.
Save sillero/4074062 to your computer and use it in GitHub Desktop.
simple javascript {{ Tag }} compiler
$compile = function($template, $scope){
var $mask = /\{\{\s*[\w.]+\s*[^\}\}]\}\}/g,
$matches = $template.match($mask),
$templateScope = [], k;
for (k in $matches) {
var $match = $matches[k].replace(/[\{\}\s]/g,'').split('.');
$templateScope.push($match);
}
for (k in $templateScope) {
var $match = $templateScope[k],
$theVar = $scope,
$theTag = $match.join('\\.');
for (var j in $match) {
if ($theVar.hasOwnProperty($match[j]))
$theVar = $theVar[$match[j]];
else
$theVar = '';
}
$theTag = new RegExp('\\{\\{\\s*'+$theTag+'\\s*[^\\}\\}]\\}\\}',"g");
$template = $template.replace($theTag, $theVar);
}
return $template;
}
/*
$template = '<div class="{{ className }}">{{ item.label }}</div>';
$scope = {
className: 'title',
item: {
label: 'this is a label'
}
};
$compile($template, $scope);
>>> <div class="title">this is a label</div>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment