Accueil > > > 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
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
Commentaires et avis
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érer du code 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 à savoir comment je peux faire pour gérer les boutons submits lorsque j'ai plusieurs formulaires dans une page (template)
Prob avec preg_replace() [ par Kevergeek ]
Voici mon code : <?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
|
Derniers Blogs
SESSION SILVERLIGHT 5 3D : SLIDES ET DEMOSSESSION SILVERLIGHT 5 3D : SLIDES ET DEMOS par Groc
Durant les techdays, j'ai eu le plaisir d'animer une session sur Silverlight 5 et la 3D avec Simon Ferquel. Comme promis, voici nos slides et mes démos (celles avec le viper BSG) ici et là. Pour mémoire, les démos utilisent toutes le viper BSG...
Cliquez pour lire la suite de l'article par Groc [TECHDAYS 2012] SESSION WEBMATRIX 2 : LE COUTEAU SUISSE GRATUIT POUR VOS DéVELOPPEMENTS WEB - SLIDES[TECHDAYS 2012] SESSION WEBMATRIX 2 : LE COUTEAU SUISSE GRATUIT POUR VOS DéVELOPPEMENTS WEB - SLIDES par gpommier
Suite à la session que j'ai présenté sur WebMatrix 2, vous pouvez trouver les slides ici, ainsi que les démos en packages nuget : démos1 et démos2 J'en profite pour remercier chaleureusement tous ceux qui sont venus très nombreux à cette sess...
Cliquez pour lire la suite de l'article par gpommier [SHAREPOINT] LES SESSIONS TECHDAYS 2012.[SHAREPOINT] LES SESSIONS TECHDAYS 2012. par Patrick Guimonet
Voici donc pour ceux qui n'ont pas pu venir, ou ceux qui n'ont pas pu toutes les suivre la liste des sessions SharePoint aux TechDays 2012, que je mettrais à jour dès que les liens des vidéo seront disponibles. Ou ici : http...
Cliquez pour lire la suite de l'article par Patrick Guimonet TECHDAYS PARIS 2012 : SESSION PLEINIèRE JOUR 3TECHDAYS PARIS 2012 : SESSION PLEINIèRE JOUR 3 par ROMELARD Fabrice
Speaker: Bernard Ourghanlian Cette session est comme chaque jour transmise en live par BrainSonic, et j'ai donc suivi cette troisième pleinière par ce moyen sur mon iPad . Elle est dédiée comme chaque année à la mise en perspective de l'é...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice MISHRA READER : UN LECTEUR RSS TRèS ZUNE STYLE EN OPEN SOURCE !MISHRA READER : UN LECTEUR RSS TRèS ZUNE STYLE EN OPEN SOURCE ! par Vko
Hier durant une session dédiée aux Techdays 2012, j'ai eu le plaisir d'annoncer la sortie de la Béta 2 de Mishra Reader. C'est quoi ? Pour les utilisateurs, c'est une vraie expérience de lecture de flux RSS sur Windows. Rien à voir avec les produit...
Cliquez pour lire la suite de l'article par Vko
Logiciels
Academy System (17.2.1.0)ACADEMY SYSTEM (17.2.1.0)Logiciel de gestion des établissements.
- élèves/étudiants (inscription, dossier, absence...)
-... Cliquez pour télécharger Academy System Easy-Planning (1.0.0.1)EASY-PLANNING (1.0.0.1)Basé sur les mêmes principes que MyPlanning, Easy-Planning permet de créer des plannings sous la ... Cliquez pour télécharger Easy-Planning COLLECTOR PLUS (3.00B)COLLECTOR PLUS (3.00B)COLLECTOR PLUS version 3.00B est un logiciel utilisant une base de données alimentée par :
- L... Cliquez pour télécharger COLLECTOR PLUS PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA TV DEVIENS HELLLOOO FLASH
LA TV SUR VOTRE ORDINATEUR.
Toute une plateforme Multi... Cliquez pour télécharger PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO LettresFaciles 2011 (8.0.0.1)LETTRESFACILES 2011 (8.0.0.1)LettresFaciles est un logiciel facilitant la création et la rédaction de lettres types.
Son inte... Cliquez pour télécharger LettresFaciles 2011
|