Skip to content

Instantly share code, notes, and snippets.

@cmilfont
Created September 17, 2011 19:58
Show Gist options
  • Select an option

  • Save cmilfont/1224299 to your computer and use it in GitHub Desktop.

Select an option

Save cmilfont/1224299 to your computer and use it in GitHub Desktop.

Revisions

  1. cmilfont created this gist Sep 17, 2011.
    48 changes: 48 additions & 0 deletions engine.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    var objeto = {
    nome: "Christiano Milfont", telefone: "23423423", idade: 18,
    paginacao: function(name) { return name; }
    };

    var template = "<div> #{paginacao(nome)} #{nome} \
    - #{telefone} - #{ (idade >= 18)? \"permitido\": \"proibido\" }</div>";

    function Engine(tmpl) {
    var _pattern = /\#\{([^}]+)\}/g;
    var _json = {};
    this.compiled;
    this.mapa = {};

    var copiar = function(origem, destino) {
    for(var propriedade in origem) {
    destino[propriedade] = origem[propriedade];
    }
    };

    this.parse = function(json) {
    var self = this;
    _json = json;
    return this.compiled.replace(_pattern, function(match, value, index){
    var parser = self.mapa[value];
    return parser(json, copiar);
    });
    };

    this.construir = function(index, expression) {
    var corpo = "copiar(self, this);";
    corpo += (" return " + expression + ";");
    this.mapa[index] = new Function("self", "copiar", corpo);
    };

    this.compile = function() {
    var self = this;
    this.compiled = tmpl.replace(_pattern, function(match, expression, index){
    self.construir(index, expression);
    return "#{" + index + "}";
    });
    return this;
    }
    }

    var engine = new Engine(template).compile();
    console.log(engine);
    engine.parse(objeto);