Production Level Knowledge & Tips

  1. プログラミング
  2. 9 view

[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

プログラミングの最近記事

  1. How to bring columns not GROUP BY key from ne…

  2. HiveでGROUP BYを伴うサブクエリのネストからGROUP BYのキー以外のカラムを…

  3. How to drop Hive’s External Table

  4. HiveでExternal Tableを削除する方法メモ

  5. [触ってみた]Microsoft Quantum Development Kit

関連記事

PAGE TOP