Created
November 14, 2012 19:06
-
-
Save sillero/4074062 to your computer and use it in GitHub Desktop.
simple javascript {{ Tag }} compiler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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