begin process at 2012 02 11 15:54:50
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Divers

 > FILTPL: TEMPLATE PHP, MINIMAL, SIMPLE, RÉCURSIF, À PARTIR D'UN ARBRE DE TABLEAUX

FILTPL: TEMPLATE PHP, MINIMAL, SIMPLE, RÉCURSIF, À PARTIR D'UN ARBRE DE TABLEAUX


 Information sur la source

Note :
9 / 10 - par 1 personne
9,00 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10
Catégorie :Divers Classé sous :template Niveau :Initié Date de création :30/08/2006 Date de mise à jour :30/08/2006 02:23:53 Vu :3 247

Auteur : guykastenbaum

Ecrire un message privé
Commentaire sur cette source (1)
Ajouter un commentaire et/ou une note

 Description

Encore un systeme de template, de meme syntaxe que phplib ou phpbb :
mais il se comporte mieux sur les blocks optionnels.
Il faut utiliser à fond les tableaux php qui sont très pratiques (et var_dump..)

exemple : à partir de deux contenus, un chaine html et d'un tableau :
print filtpl_compile(
  "{a}<!-- BEGIN t -->{e}<!-- END t -->",
  array(a => "P",t => array(0=>array(e=>"H"),1=>array(e=>"P"))));
affich e "PHP"

Un block peut être considéré comme un IF ou un LOOP suivant que la valeur est un null, un array(), un tableau de key->val, ou un tableau numérique [i]->val.

Source

  • <?
  • // FILNET GUY KASTENBAUM 15 MARS 2006 V1.1 , ajout tags: begin end
  • // FILNET GUY KASTENBAUM 10 NOVEMBRE 2005 , V1.0
  • // filtpl.php un template aussi bien que les autres
  • //$tt=array(a => "aaa",b => "bbb",t => array(0=>array(e=>"eee"),1=>array(e=>"fff")));
  • //$tf="111{a}<!-- BEGIN t -->{e}<!-- END t --><!-- BEGIN u -->u{e}u<!-- END u -->222{b}";
  • //print filtpl_compile($tf,$tt);
  • //recursive function filtpl_compile($filtpl_tf,$filtpl_tt)
  • //input string,tree / ouput : compiled string
  • // filtpl_tf = string of the template file
  • // filtpl_tt = array of values or subarrays
  • function filtpl_compile($filtpl_tf,$filtpl_tt){
  • if (!$filtpl_tt) return("");//unwanted branch I presume
  • if (!is_array($filtpl_tt)) return($filtpl_tf);//like a bug
  • if (preg_match('#<!-- BEGIN (\w+) -->#i', $filtpl_tf , $filtpl_m , PREG_OFFSET_CAPTURE))
  • {
  • $filtpl_before=substr($filtpl_tf,0,$filtpl_m[0][1]);
  • $filtpl_tag=$filtpl_m[1][0];//tag for first begin
  • $filtpl_after=substr($filtpl_tf,$filtpl_m[0][1]+strlen("<!-- BEGIN $filtpl_tag -->"));
  • if (!preg_match("#<!-- END $filtpl_tag -->#i",$filtpl_after, $filtpl_m , PREG_OFFSET_CAPTURE)) die("begin $filtpl_tag with no end");
  • $filtpl_loop=substr($filtpl_after,0,$filtpl_m[0][1]);
  • $filtpl_after=substr($filtpl_after,$filtpl_m[0][1]+strlen("<!-- END $filtpl_tag -->"));
  • //string is splitted in before.loop.after -- lets recurse!
  • $filtpl_tf=$filtpl_before;
  • $filtpl_tf.=$filtpl_tt[$filtpl_tag]["begin"];
  • //is it a loop or just a if ? (ugly test : if [0] exists it is supposed to be a loop)
  • if ($filtpl_tt[$filtpl_tag][0])
  • foreach ($filtpl_tt[$filtpl_tag] as $filtpl_tt_sub) //lets loop
  • $filtpl_tf.=filtpl_compile($filtpl_loop,$filtpl_tt_sub);
  • else // lets do the unique loop
  • $filtpl_tf.=filtpl_compile($filtpl_loop,$filtpl_tt[$filtpl_tag]);
  • $filtpl_tf.=$filtpl_tt[$filtpl_tag]["end"];
  • $filtpl_tf.=filtpl_compile($filtpl_after,$filtpl_tt); //recurse the afterloop
  • }
  • //substitute known values of root level
  • foreach ($filtpl_tt as $filtpl_key=>$filtpl_val)
  • if (!is_array($filtpl_val))
  • $filtpl_tf=preg_replace("/\{$filtpl_key\}/i",$filtpl_val,$filtpl_tf);
  • $filtpl_tf=preg_replace("/\{\w+\}/i","",$filtpl_tf);//zap unknown values
  • return($filtpl_tf);
  • }
  • /*--- example , just for the eyes ---
  • //$tf=join("",file("example.htm"));
  • $tf="{title}
  • <!-- BEGIN prd_list -->
  • {column_one} {column_two}
  • <!-- BEGIN if_ok -->{msg}<!-- END if_ok -->
  • <!-- END prd_list -->
  • ";
  • $tt=array();//create a string and an array
  • $tt["titre"]= "hello world";//root level
  • $tt["prd_list"]= array();//loop
  • $list=mysql_query("select column_one,column_two from a_table");
  • while ($rs=mysql_fetch_array($list)){
  • $tt_prd_list= array();//loop level data
  • foreach (array_keys($rs) as $chp)
  • $tt_prd_list[$chp]=$rs[$chp]; //fill each items
  • if ($rs["column_one"]==1) // "if" clause
  • $tt_prd_list["if_ok"]=array("msg"=>"OK");
  • array_push($tt["prd_list"],$tt_prd_list);//fill loop
  • }
  • //debug : print"<pre>";print_r($tt);print"</pre>";
  • print filtpl_compile($tf,$tt);//pparse in other langages
  • */
  • ?>
<?
// FILNET GUY KASTENBAUM 15 MARS 2006 V1.1 , ajout tags: begin end
// FILNET GUY KASTENBAUM 10 NOVEMBRE 2005 , V1.0
// filtpl.php un template aussi bien que les autres
//$tt=array(a => "aaa",b => "bbb",t => array(0=>array(e=>"eee"),1=>array(e=>"fff")));
//$tf="111{a}<!-- BEGIN t -->{e}<!-- END t --><!-- BEGIN u -->u{e}u<!-- END u -->222{b}";
//print filtpl_compile($tf,$tt);	

//recursive function filtpl_compile($filtpl_tf,$filtpl_tt)
//input string,tree / ouput : compiled string
// filtpl_tf = string of the template file
// filtpl_tt = array of values or subarrays
function filtpl_compile($filtpl_tf,$filtpl_tt){
	if (!$filtpl_tt) return("");//unwanted branch I presume
	if (!is_array($filtpl_tt)) return($filtpl_tf);//like a bug
	if (preg_match('#<!-- BEGIN (\w+) -->#i', $filtpl_tf , $filtpl_m , PREG_OFFSET_CAPTURE))
	{
		$filtpl_before=substr($filtpl_tf,0,$filtpl_m[0][1]);
		$filtpl_tag=$filtpl_m[1][0];//tag for first begin
		$filtpl_after=substr($filtpl_tf,$filtpl_m[0][1]+strlen("<!-- BEGIN $filtpl_tag -->"));
		if (!preg_match("#<!-- END $filtpl_tag -->#i",$filtpl_after, $filtpl_m , PREG_OFFSET_CAPTURE)) die("begin $filtpl_tag with no end");
		$filtpl_loop=substr($filtpl_after,0,$filtpl_m[0][1]);
		$filtpl_after=substr($filtpl_after,$filtpl_m[0][1]+strlen("<!-- END $filtpl_tag -->"));
		//string is splitted in before.loop.after -- lets recurse!
		$filtpl_tf=$filtpl_before;
		$filtpl_tf.=$filtpl_tt[$filtpl_tag]["begin"];
		//is it a loop or just a if ? (ugly test : if [0] exists it is supposed to be a loop)
		if ($filtpl_tt[$filtpl_tag][0])
			foreach ($filtpl_tt[$filtpl_tag] as $filtpl_tt_sub) //lets loop
				$filtpl_tf.=filtpl_compile($filtpl_loop,$filtpl_tt_sub);
		else // lets do the unique loop
			$filtpl_tf.=filtpl_compile($filtpl_loop,$filtpl_tt[$filtpl_tag]);
		$filtpl_tf.=$filtpl_tt[$filtpl_tag]["end"];
		$filtpl_tf.=filtpl_compile($filtpl_after,$filtpl_tt); //recurse the afterloop
	}
	//substitute known values of root level
	foreach ($filtpl_tt as $filtpl_key=>$filtpl_val)
		if (!is_array($filtpl_val))
			$filtpl_tf=preg_replace("/\{$filtpl_key\}/i",$filtpl_val,$filtpl_tf);
	$filtpl_tf=preg_replace("/\{\w+\}/i","",$filtpl_tf);//zap unknown values
	return($filtpl_tf);
}

/*--- example , just for the eyes ---
//$tf=join("",file("example.htm")); 
$tf="{title}
<!-- BEGIN prd_list -->
{column_one} {column_two}
	<!-- BEGIN if_ok -->{msg}<!-- END if_ok -->
<!-- END prd_list -->
";
$tt=array();//create a string and an array
$tt["titre"]= "hello world";//root level
$tt["prd_list"]= array();//loop
$list=mysql_query("select column_one,column_two from a_table");
while ($rs=mysql_fetch_array($list)){
	$tt_prd_list= array();//loop level data
	foreach (array_keys($rs) as $chp)
		$tt_prd_list[$chp]=$rs[$chp]; //fill each items
	if ($rs["column_one"]==1) // "if" clause
		$tt_prd_list["if_ok"]=array("msg"=>"OK");
	array_push($tt["prd_list"],$tt_prd_list);//fill loop
}
//debug : print"<pre>";print_r($tt);print"</pre>";
print filtpl_compile($tf,$tt);//pparse in other langages
*/
?>

 Conclusion

que manque-t-il ? non il ne faut pas surcharger ce code par des options de formatage dont le graphiste se fout, ou des fonctions d'enrobage. éventuellement il manque une fonction else.

j'adore ce code :-) il marche en prod sur pas mal de mes sites.


 Historique

30 août 2006 02:23:53 :
Petit nettoyage de source pour qu'il soit un peu plus clair pour mon premier Post...

 Sources de la même categorie

Source avec Zip COMPTEUR DE CLIQUE PHP AVEC JQUERY par devgoneti
Source avec Zip LIVRE D'OR SIMPLE (POUR DÉBUTANT) par devgoneti
Source avec Zip SCRIPT TRAVAUX POUR VOTRE SITE par FleuryK
Source avec Zip Source avec une capture EL COYOTOS LIVRE D'OR PHP 5 par elcoyotos
COMPTEUR DE VISITE - FICHIER TXT - CODE MINIMAL par SuperChouquette

 Sources en rapport avec celle ci

Source avec Zip SIMPLETEMPLATE par thunderhunter
Source avec Zip MOTEUR DE TEMPLATE PHPBB3 SIMPLIFIÉ EN PHP5 par gagah1
Source avec Zip GÉNÉRER DES DOCUMENTS OPENOFFICE (OPENDOCUMENT) OU WORD 2007... par oloynet
Source avec Zip Source avec une capture ODTPHP - UPDATE POUR PHP 5.2.7 ET + par stailer
Source avec Zip CHANGEMENT DE TEMPLATE par starkeny

Commentaires et avis

Commentaire de Elkouo le 05/10/2006 08:40:21

Un petit tuto serait le bienvenu si tu veux que ton moteur de template soit adopté ...
Certes, il ressemble à phplib et phpbb mais explique avec un peu plus de détail et d'exemple ses atouts

Merci

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

Template :: Comment ça marche??? [ par Adagyo ] Salut @ tous,Je souhaiterais proposer au utilisateur plusieurs theme d'affichage de mes page web... Pour cela, j'ai essayé de décortiquer un peux vBul template.inc [ par joedalton ] bonjourVoila, je possede un fichier template.inc qui me permet de définir ma classe template, mais le probleme c'est que ce fichier est valable pour l template aide [ par thedentiste ] Voila est ce que quelqu'un pourrais m'aider pour utlisation de template j'ai chope plein de tuto mais je trouve pas ce qu'il le faut je cherche a fair Template phplib [ par TuXAveRy ] Bonjour,Voila j'ai un problème de logique assez basic :/J'utilise smarty depuis quelque temps déjà et pour des raisons technique je souhaiterais passe php dans template [ par BirD ] hello, une tite question par rapport aux templates : peut -on ins&#233;rer du code&nbsp; php dans le fichier de template et faire que ca fonctionne ? template [ par Urukai1 ] bonjour a tous g une question sur les termplates j'utilise celle de PHPLib en gros j'ai fait un modele de page web a laquelle j'applique des valeurs Comment gérer les boutons submits [ par alaise ] Bonjour,Je cherche &#224; savoir comment je peux faire pour g&#233;rer les boutons submits lorsque j'ai plusieurs formulaires dans une page (template) Prob avec preg_replace() [ par Kevergeek ] Voici mon code : &lt;?php $file = "templates/default/test.tpl"; $template['TITLE'] = "titre"; $template['TEXT'] = "blabla"; $file = file_get_content Récupérer du code d'une page html [ par Metaldark ] Salut ! [;)] Bon, j'explique mon problème : j'ai fait un script qui gere des templates et génére des pages html statiques.Par exemple, le template es probleme liens internes [ par greg975 ] bonjour à tous, debutant en programmation je met sur pieds un petit site. Ainsi j'ai telécharger un template (design) que je veux bien modifier.Le dos


Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Février 2012
LMMJVSD
  12345
6789101112
13141516171819
20212223242526
272829    

Consulter la suite du CalendriCode

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 1,482 sec (4)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales