Mini moteur de template

Description

Ceci est un mini moteur de template. L'idée met venue de Smarty en php. Je n'ai implémenté que la condition if et la boucle while. Voici la synatxe:
- {if condition}{/}
- {while condition}{/}
- {$var}
Pour passer une variable, utiliser vdata:
test = new JTemplate();
test.vdata={myvar:"sa marche", test:3};

Source / Exemple :


function JTemplate() {}
JTemplate.prototype={
	vdata:null,
	str_var:"this.vdata.",
	p_this: new RegExp("[\$]","gmi"),
	patern: new RegExp("(\{(/|(if|while) ([^\{\}]+)|([\$])([^\{\} ]+))\})","gmi"),
	error:null,
	parse: function(data) {
		var datab=data.split(this.patern);
		var action=[];
		var strout="";
		for (var i=0; i < datab.length; i++ )
		{
			if ( datab[i].match(this.patern) )
			{
				if ( datab[i+2] == "if" )
				{
					if ( !action.length || (action.length && action[action.length-1].v) )
					{
						test=eval(datab[i+3].replace(this.p_this,this.str_var));
						action.push({t:"if",v:test});
					}
					else
						action.push({t:"if",v:false});
				}
				else if ( datab[i+2] == "while" )
				{
					if ( !action.length || (action.length && action[action.length-1].v) )
					{
						test=eval(datab[i+3].replace(this.p_this,this.str_var));
						action.push({t:"while",v:test,p:i});
					}
					else
						action.push({t:"while",v:false,p:i});
				}
				else if ( datab[i+1] == "/" )
				{
					if ( !action.length )
					{
						this.error="error";
						alert(this.error);
						return false;
					}
					else if (action[action.length-1].t != "while" || !action[action.length-1].v )
						action.pop();
					else if (action[action.length-1].t == "while")
					{
						i=action[action.length-1].p-6;
						action.pop();
					}
				}
				else if ( datab[i+4] == "$" )
				{
					if ( !action.length || ( action.length && action[action.length-1].v ))
					{
						myvar=(this.str_var+datab[i+5]).replace(this.p_this,this.str_var);
						myvar=eval(myvar);
						strout+=myvar;
					}
				}
				i+=5;
			}
			else
			{
				if ( !action.length || ( action.length && action[action.length-1].v ))
					strout+=datab[i];
			}
		}
		return strout;
	}
}

str="start encore un test {if 1} <ul>{while $test++<5}\
<li>loop haha {$test} </li>{/}</ul> end {/} hihhiih";

test = new JTemplate();
test.vdata={myvar:"sa marche", test:3};
document.write(str+"<hr />");
document.write(test.parse(str));

Conclusion :


Have fun

Codes Sources

A voir également