PROJET AUTOBLOG


Tontof

Site original : Tontof

⇐ retour index

8 : KrISS aaaa : html

mardi 26 mars 2024 à 19:04
L'idée de Tom Butler pour la génération des pages PHP est vraiment originale. Son implémentation avec Transphporm montre une approche différente des autres projets plus classiques comme Twig. À ma connaissance c'est vraiment le seul projet qui utilise cette idée et théoriquement c'est très élégant dans le monde de la programmation object.

Pour mon approche plus impérative avec KrISS aaaa, j'ai imaginé l'utilisation d'un tableau associatif pour manipuler le code html à générer. Pour cela j'ai donc fait plusieurs fonctions pour transformer du code html en tableau associatif et vice versa.

En pratique, ça donne :
<?php include('src/helpers/html/html.php');

$string '
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Title</title>
  </head>
  <body>
    body
  </body>
</html>
'
;
$array html_to_array($string);
var_dump(array_to_html($array));
$arraySimplified array_html_simplify($array);
$arraySimplified['html']['head']['title'] = "New title";
$arraySimplified['html']['body'] = [["p" => "new body"]];
$arraySimplified['html']['body'][] = ["p" => "add body"];
var_dump($arraySimplified);
var_dump(array_to_html($arraySimplified)); ?>



Ce qui donne comme résultat :
string(110) "<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Title</title></head><body>body</body></html>"
array(2) {
  '!DOCTYPE' =>
  array(1) {
    '@' =>
    array(1) {
      [0] =>
      string(4) "html"
    }
  }
  'html' =>
  array(3) {
    '@' =>
    array(1) {
      'lang' =>
      string(2) "en"
    }
    'head' =>
    array(2) {
      'meta' =>
      array(1) {
        '@' =>
        array(1) {
          'charset' =>
          string(5) "utf-8"
        }
      }
      'title' =>
      string(9) "New title"
    }
    'body' =>
    array(2) {
      [0] =>
      array(1) {
        'p' =>
        string(8) "new body"
      }
      [1] =>
      array(1) {
        'p' =>
        string(8) "add body"
      }
    }
  }
}
string(140) "<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>New title</title></head><body><p>new body</p><p>add body</p></body></html>"



Une remarque importante, cela ne génère pas de code html avec des retours à la ligne et des indentations mais c'est un choix volontaire. Bien sûr cela peut poser problème avec les affichages inline-block qui ne réagissent pas exactement de la même façon s'il y a des espaces entre les balises ou non.

Le but étant de rester minimaliste, ce comportement est donc voulu !
It's not a bug it's a feature!