[CoffeeScript]簡易的なテンプレートエンジンを作ってみた

これを
<script type="text/javascript">
people = [];
(function () {
{repeat}
people.push({
name: "#{people[index].name}"
});
{repeat}
})();
</script>
このようにしたくて、簡単に作ってみた。
<script type="text/javascript">
people = [];
(function () {
{repeat}
people.push({
name: "suzuki"
});

people.push({
name: "tanaka"
});

people.push({
name: "bob"
});

})();
</script>
以下がcoffee scriptのクラス。
class Tag constructor: (data, text) -> @validated = data @text = text @keywords = [ /^numpeople$/ /^people$/ /^people\[[0-9]\].name$/ ] validate: (str) -> for keyword in @keywords if keyword.test(str) return true return false string_to_value: (str) ->                 # Syntax Sugar if str == 'names' names = [] for people, i in @validated.people names.push "'#{people.name}'" names.toString() # Normal replace                 else if @validate(str) eval("this.validated." + str) else str replace: () -> # Replace repeatable line targets = @text.match(/{repeat}([\n\r]|.)*?{repeat}/) if targets != null target = targets[0] insert_line = target.substring(8,target.length-9) result = "" for people, i in @validated.items replaced_insert_line = insert_line.replace(/{index\+1}/g, i+1) replaced_insert_line = replaced_insert_line.replace(/index/g, i) result += replaced_insert_line @text = @text.replace(/{repeat}([\n\r]|.)*?{repeat}/, result) # Replace variable targets = @text.match(/#{.*?}/g) if targets != null for target in targets pattern = target.replace(/\[/g, '\\[') pattern = pattern.replace(/\]/g, '\\]') regex = new RegExp(pattern, 'g') @text = @text.replace(regex, @string_to_value(target.substring(2,target.length-1))) get_tag: () -> @text exports.Tag = Tag
zuqqhi2

某Web系の会社でエンジニアをやっています。 学術的なことに非常に興味があります。 趣味は楽器演奏、ジョギング、読書、料理などなど手広くやっています。