Created — forked from cmilfont/engine.js

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Turma 3 - Exercicio 2 - Engine de Template

View engine.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.