Moteur de template Twig

Fermé
chabinot Messages postés 321 Date d'inscription mardi 10 novembre 2015 Statut Membre Dernière intervention 22 mars 2024 - 15 avril 2018 à 13:00
chabinot Messages postés 321 Date d'inscription mardi 10 novembre 2015 Statut Membre Dernière intervention 22 mars 2024 - 16 avril 2018 à 07:18
Bonjour,
Je suis en train de tester le moteur de template Twig.
Dans mon application, j'ai une classe Month comme suit :
<?php 

namespace Calendrier;

class Month extends Date
{
   public $year;
   public $month;
   public $holidays  = [];
   public $feries    = [];
   public $cathol    = [];
   public $catho     = [];
   public function __construct(?int $year = null)
   {
      if ($year === null) {
         $year = intval(date('Y'));
      }
      $this->year = $year;
   }
   public function previousYear()
   {
      $year = $this->year - 1;

      return $year;
   }
   public function nextYear()
   {
      $year = $this->year + 1;

      return $year;
   }
   /**
    * Retourne le tableau des libellés jours fériés
    *
    * @return array
    */
   public function getHolidays() : array
   {
      $holidays = [
         "Jour de l'an",
         "Lundi de pâques",
         "Lundi de pentecôte",
         "Ascension",
         "Fête du travail",
         "Victoire des alliés",
         "Fête nationale",
         "Assomption",
         "Toussaint",
         "Armistice 1918",
         "Noël",
      ];

      $this->holidays = $holidays;

      return $this->holidays;
   }
   /**
    * Retourne le tableau des jours fériés
    *
    * @return array
    */
   public function getFeries() : array
   {
      $feries[] = $this->year . '0101';                          // Jour de l'an
      $feries[] = $this->lundiPaques($this->year);               // Lundi de pâques
      $feries[] = $this->lundiPentecote($this->year);            // Lundi de pentecôte
      $feries[] = $this->ascension($this->year);                 // Ascension
      $feries[] = $this->year . '0501';                          // Fête du travail
      $feries[] = $this->year . '0508';                          // Victoire des alliés
      $feries[] = $this->year . '0714';                          // Fête nationale
      $feries[] = $this->year . '0815';                          // Assomption
      $feries[] = $this->year . '1101';                          // Toussaint
      $feries[] = $this->year . '1111';                          // Armistice 1918
      $feries[] = $this->year . '1225';                          // Noël

      $this->feries = $feries;

      return $this->feries;
   }
   /**
    * Retourne le noùbre de postes du tableau feries
    *
    * @return integer
    */
   public function countFeries() : int
   {
      return $count = count($this->feries);
   }
   /**
    * Retourne le tableau des jours des fêtes catholiques
    *
    * @return array
    */
   public function getCathol() : array
   {
      $cathol = [
         "Épiphanie",
         "Chandeleur",
         "Mardi gras",
         "Cendres",
         "Annonciation",
         "Rameaux",
         "Jeudi saint",
         "Vendredi saint",
         "Pâques",
         "Pentecôte",
         "Fête des morts"
      ];

      $this->cathol = $cathol;

      return $this->cathol;
   }
   /**
    * Retourne le tableau des fêtes catholiques
    *
    * @return array
    */
   public function getCatho() : array
   {
      $catho[] = $this->epiphanie($this->year);                // Épihanie
      $catho[] = $this->chandeleur($this->year);               // Chandeleur
      $catho[] = $this->mardiGras($this->year);                // Mardi gras
      $catho[] = $this->cendres($this->year);                  // Mercredi des cendres
      $catho[] = $this->annonciation($this->year);             // Annonciation à la vierge
      $catho[] = $this->rameaux($this->year);                  // Dimanche des rameaux
      $catho[] = $this->jeudiSaint($this->year);               // Jeudi saint
      $catho[] = $this->vendrediSaint($this->year);            // Vendredi saint
      $catho[] = $this->paques($this->year);                   // Pâques
      $catho[] = $this->pentecote($this->year);                // Pentecôte
      $catho[] = $this->year . '1102';                         // Fête des morts

      $this->catho = $catho;

      return $this->catho;
   }
   /**
    * Retoune le nombre de postes du tableau catho
    *
    * @return integer
    */
   public function countCatho() : int
   {
      return $count = count($this->catho);
   }
   /**
    * Retourne le libellé du mois
    *
    * @param Int $index
    * @return string
    */
   public function rtvMonthName(Int $index) : string
   {
      return $this->months[$index];
   }
   /**
    * Retourne le nombre de jours dans le mois
    *
    * @param Int $index
    * @return integer
    */
   public function getNumDays(Int $index) : int
   {
      return $index == 2 ? ($this->year % 4 ? 28 : ($this->year % 100 ? 29 : ($this->year % 400 ? 28 : 28))) : (($index - 1) % 7 % 2 ? 30 : 31);
   }
   /**
    * Affiche le premier semestre
    *
    * @return void
    */
   public function getFirstSemDays() 
   {
      $year   = $this->year;
      $toDay  = date('Ymd');
      $result = '';
      for ($mo = 1; $mo <= 1 ; $mo++) {
         $result .= '<div class="month">';
         $result .= '<div class="month__head">';
         $result .= '<i class="fa fa-calendar"></i>';
         $result .= '<span class="month__head-month">';
         $result .= $this->rtvMonthName($mo);
         $result .= '</span>';
         $result .= '<span class="month__head-day">jour</span>';
         $result .= '<span class="month__head-sem">sem</span>';
         $result .= '</div><!-- /.month__head-->';
         for ($i = 1; $i <= $this->getNumDays($mo); $i++) { 
            $x    = ($i < 10 ? '0'    : '') . $i;
            $mois = ($mo < 10 ? '0': '') . $mo;
            $date = $year . $mois . $x;
            $j    = date('j', strtotime($date));
            $n    = date('N', strtotime($date));
            $w    = intval(date('W', strtotime($date)));
            $doy  = intval(strftime("%j", strtotime($date)));
            $day  = $this->days[$n];
            
            if (in_array($date, $this->getFeries())) {
               $result .= '<div class="days green">';
            } elseif ($date == $toDay) {
               $result .= '<div class="days yellow">';
            } else {
               $result .= '<div class="days">';
            }
            $result .= '<span class="day">' . $day . '</span>';
            $result .= '<span class="nday">' . $j . '</span>';
            $result .= '<span class="jour">' . $doy . '</span>';
            $result .= '<span class="sem">' . $w . '</span>';
            $result .= '</div><!-- /.days -->';         
         }
         $result .= '</div><!-- /.month -->';

         echo $result;
      }
   }
   /**
    * Affiche le deuxième semestre
    *
    * @return void
    */
   public function getSecondSemDays()
   {
      $year = $this->year;
      $toDay = date('Ymd');
      for ($mo = 7; $mo <= 12; $mo++) {
         $result = '';
         $result .= '<div class="month">';
         $result .= '<div class="month__head">';
         $result .= '<i class="fa fa-calendar"></i>';
         $result .= '<span class="month__head-month">';
         $result .= $this->rtvMonthName($mo);
         $result .= '</span>';
         $result .= '<span class="month__head-day">jour</span>';
         $result .= '<span class="month__head-sem">sem</span>';
         $result .= '</div><!-- /.month__head-->';
         for ($i = 1; $i <= $this->getNumDays($mo); $i++) {
            $x = ($i < 10 ? '0' : '') . $i;
            $mois = ($mo < 10 ? '0' : '') . $mo;
            $date = $year . $mois . $x;
            $j = date('j', strtotime($date));
            $n = date('N', strtotime($date));
            $w = intval(date('W', strtotime($date)));
            $doy = intval(strftime("%j", strtotime($date)));
            $day = $this->days[$n];

            if (in_array($date, $this->getFeries())) {
               $result .= '<div class="days green">';
            } elseif ($date == $toDay) {
               $result .= '<div class="days yellow">';
            } else {
               $result .= '<div class="days">';
            }
            $result .= '<span class="day">' . $day . '</span>';
            $result .= '<span class="nday">' . $j . '</span>';
            $result .= '<span class="jour">' . $doy . '</span>';
            $result .= '<span class="sem">' . $w . '</span>';
            $result .= '</div><!-- /.days -->';
         }
         $result .= '</div><!-- /.month -->';

         echo $result;
      }
   }
   public function dspFeries()
   {
      $array1 = $this->getHolidays();
      $array2 = $this->getFeries();
      array_multisort($array2, $array1);
      // Formattage de l'affichage
      for ($i = 0; $i < $this->countFeries(); $i ++) { 
         $result = '<div class="feries__libday">';
         $result .= '<div class="feries__libday-day">';
         $result .= $array1[$i];
         $result .= '</div><!-- /.feries__libday-day -->';
         $result .= '<div class="feries__libday-jour">';
         $result .= $this->rtvWeekDay($array2[$i]);
         $result .= '</div><!-- /.feries__libday-jour -->';
         $result .= '<div class="feries__libday-numday">';
         $result .= $this->rtvDay($array2[$i]);
         $result .= '</div><!-- /.feries__libday-numday -->';
         $result .= '<div class="feries__libday-month">';
         $result .= $this->rtvMonth($array2[$i]);
         $result .= '</div><!-- /.feries__libday-month -->';
         $result .= '</div><!-- /.feries__libday -->';

         echo $result;
      }
   }
   public function dspCatho()
   {
      $array1 = $this->getCathol();
      $array2 = $this->getCatho();
      $count  = count($array2);
      array_multisort($array2, $array1);
      // Formattage de l'affichage
      for ($i = 0; $i < $this->countCatho(); $i++) {
         $result = '<div class="catho__libday">';
         $result .= '<div class="catho__libday-day">';
         $result .= $array1[$i];
         $result .= '</div><!-- /.catho__libday-day -->';
         $result .= '<div class="catho__libday-jour">';
         $result .= $this->rtvWeekDay($array2[$i]);
         $result .= '</div><!-- /.catho__libday-jour -->';
         $result .= '<div class="catho__libday-numday">';
         $result .= $this->rtvDay($array2[$i]);
         $result .= '</div><!-- /.catho__libday-numday -->';
         $result .= '<div class="catho__libday-month">';
         $result .= $this->rtvMonth($array2[$i]);
         $result .= '</div><!-- /.catho__libday-month -->';
         $result .= '</div><!-- /.catho__libday -->';

         echo $result;
      }
   } 
}

Je veux afficher le premier semestre dans home.twig, j'essaye de le faire comme cela :
1- fichier index.php
<?php 
// Autoloading
require './src/bootstrap.php';


// Initialisations
// Dates
$date  = new Calendrier\Date();
$today = $date->getDate();
$sem   = $date->getWeek();
$day   = $date->getDayNum();
$reste = $date->reste();


// Mois
$month     = new Calendrier\Month($_GET['year'] ?? null);
$year      = $_GET['year'] ?? date('Y');
$dref      = $year . '0630';

//$semestre1 = $month->getFirstSemDays();

//$sem2    = $month->getSecondSemDays();

$previous  = $month->previousYear();
$next      = $month->nextYear();

$title     = 'Calendrier';
$titre     = $title . ' ' . $year;

// URL
$host = $_SERVER['HTTP_HOST'];
$uri = $_SERVER['REQUEST_URI'];
$url = sprintf("%s%s%s", "http://", $host, $uri);
$http = explode('/', $url);
$url = $http[0] . '//' . $http[2] . '/' . $http[3];

// Routing
$page = 'home';
if (isset($_GET['p'])) {
   $page = $_GET['p'];
}

// Rendu du template
$loader = new Twig_Loader_Filesystem(__DIR__ . '/templates');
$twig   = new Twig_Environment($loader, [
   'cache' => false //__DIR__ . '/tmp'
]);

if ($page === 'home') {
   echo $twig->render('home.twig', [
      'date'     => $today,
      'sem'      => '(Semaine: ' . $sem . ')',
      'day'      => ' (Jour : ' . $day . ')',
      'reste'    => ' (' . $reste . ')',
      'titre'    => $titre,
      'title'    => $title,
      'url'      => $url,
      'previous' => $previous,
      'next'     => $next,
      'month'    => $month->getFirstSemDays()
   ]);
}

2-Fichier home.twig :
{% extends 'layout.twig' %}

{% block head %}
   <title>{{ title }}</title>
{% endblock %}

{% block content%}
   <div class="container">
      <header class="header">
      <div class="header__top">
         <div class="header__top-date">
         {{ date }} <br>
         {{ sem ~ day ~ reste }}
         </div><!-- /.header__top-date -->
         <div class="header__top-titre text-center">
            <a href="/"><i class="fa fa-calendar"></i> {{ titre }} </a>
         </div><!-- /.header__top-titre -->
         <div class="header__top-time">
            <i class="fa fa-clock-o"></i> <span id="time"><script>window.onload=dspTime('time')</script></span>
         </div><!-- /.header__top-time -->
      </div><!-- /.header__top -->
      </header><!-- /header -->
      <nav class="nav">
         <div class="previous__year">
            <a href="{{ url }}/?year={{ previous }}"><Précédent></a>
         </div><!-- /.previous__year -->
         <ul class="menu">
            <li class="active"><a href="#sem1" id="sema">Semestre 1</a></li>
            <li><a href="#sem2" id="semb">Semestre 2</a></li>
            <li><a href="#feries" id="fera">Jours fériés</a></li>
         </ul><!-- /.menu -->
         <div class="next__year">
            <a href="{{ url }}/?year={{ next }}"><Suivant></a>
         </div><!-- /.previous__year -->
      </nav><!-- /.nav -->
    <section id="sem1" class="section">
     <h1 class="text-center">Premier Semestre</h1>
     <hr class="hr">
     <div class="mois">
       {{ month }}
     </div><!-- /.mois -->
   </section><!-- /#sem1 /.section -->
   <section id="sem2" class="section">
     <h1 class="text-center">Deuxième Semestre</h1>
     <hr class="hr">
     <div class="mois">

     </div><!-- /.mois -->
   </section><!-- /#sem1 /.section -->
{% endblock %}
{% block foot %}
        <footer class="footer text-center">
          <p>© Copyright. <a href="{{ url }}">{{ title }} {{ "now" | date('Y') }}</a>. Tous Droits Réservés.</p>
        </footer><!-- /footer -->
      </div><!-- /.container -->
      <!-- Scripts -->
      <script src="js/jquery-3.2.1.min.js"></script>
      <script src="js/calend.js"></script>
   </body>
</html>
{% endblock %} 

Le résultat est qu'il affiche le premier semestre à gauche de la page alors qu'il devrait me le mettre entre
la balise
<div class="mois">
   {{ month }}
</div><!-- /. mois --> 

Merci de votre aide.
Cordialement

1 réponse

jordane45 Messages postés 38173 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 10 mai 2024 4 665
15 avril 2018 à 18:19
Bonjour,

Je ne comprend pas bien la question....

Tu dis que la valeur de {{ month }} s'affiche ... mais pas au bon endroit....
Donc ton code PHP semble bon.
Le souci vient certainement de ton template html ....

As tu essayé d'utiliser les outils de dév de ton navigateur pour essayer de voir si ton html était bon ?
En faisant "examiner l'élément" là où s'affiche ta valeur.. dans quoi est-il ? pas dans sa div ?


Pourrais tu nous donner le code "généré" de ta page ( pour ça .. tu affiches ta pages dans ton navigateur, puis tu utilises le raccourci CTRL + u ) et tu nous colles le résultat sur le forum.

Ajoutes aussi une capturé écran de ton "examiner l'élément" qu'on essaye de voir ce qui cloche.


0
chabinot Messages postés 321 Date d'inscription mardi 10 novembre 2015 Statut Membre Dernière intervention 22 mars 2024 15
16 avril 2018 à 07:18
Merci,
Si tu regardes la fonction getFirstSemDays, elle formate, grâce à une boucle, du code source, cela marche très bien dans un environnement normal (sans twig).
Ce que je veux, c'est avoir le même résultat en utilisant le moteur de template Twig (que je teste).
Je te mets le résultat de la page Ctrl+U.

<div class="month"><div class="month__head"><i class="fa fa-calendar"></i><span class="month__head-month">Janvier</span><span class="month__head-day">jour</span><span class="month__head-sem">sem</span></div><!-- /.month__head--><div class="days green"><span class="day">lundi</span><span class="nday">1</span><span class="jour">1</span><span class="sem">1</span></div><!-- /.days --><div class="days"><span class="day">mardi</span><span class="nday">2</span><span class="jour">2</span><span class="sem">1</span></div><!-- /.days --><div class="days"><span class="day">mercredi</span><span class="nday">3</span><span class="jour">3</span><span class="sem">1</span></div><!-- /.days --><div class="days"><span class="day">jeudi</span><span class="nday">4</span><span class="jour">4</span><span class="sem">1</span></div><!-- /.days --><div class="days"><span class="day">vendredi</span><span class="nday">5</span><span class="jour">5</span><span class="sem">1</span></div><!-- /.days --><div class="days"><span class="day">samedi</span><span class="nday">6</span><span class="jour">6</span><span class="sem">1</span></div><!-- /.days --><div class="days"><span class="day">dimanche</span><span class="nday">7</span><span class="jour">7</span><span class="sem">1</span></div><!-- /.days --><div class="days"><span class="day">lundi</span><span class="nday">8</span><span class="jour">8</span><span class="sem">2</span></div><!-- /.days --><div class="days"><span class="day">mardi</span><span class="nday">9</span><span class="jour">9</span><span class="sem">2</span></div><!-- /.days --><div class="days"><span class="day">mercredi</span><span class="nday">10</span><span class="jour">10</span><span class="sem">2</span></div><!-- /.days --><div class="days"><span class="day">jeudi</span><span class="nday">11</span><span class="jour">11</span><span class="sem">2</span></div><!-- /.days --><div class="days"><span class="day">vendredi</span><span class="nday">12</span><span class="jour">12</span><span class="sem">2</span></div><!-- /.days --><div class="days"><span class="day">samedi</span><span class="nday">13</span><span class="jour">13</span><span class="sem">2</span></div><!-- /.days --><div class="days"><span class="day">dimanche</span><span class="nday">14</span><span class="jour">14</span><span class="sem">2</span></div><!-- /.days --><div class="days"><span class="day">lundi</span><span class="nday">15</span><span class="jour">15</span><span class="sem">3</span></div><!-- /.days --><div class="days"><span class="day">mardi</span><span class="nday">16</span><span class="jour">16</span><span class="sem">3</span></div><!-- /.days --><div class="days"><span class="day">mercredi</span><span class="nday">17</span><span class="jour">17</span><span class="sem">3</span></div><!-- /.days --><div class="days"><span class="day">jeudi</span><span class="nday">18</span><span class="jour">18</span><span class="sem">3</span></div><!-- /.days --><div class="days"><span class="day">vendredi</span><span class="nday">19</span><span class="jour">19</span><span class="sem">3</span></div><!-- /.days --><div class="days"><span class="day">samedi</span><span class="nday">20</span><span class="jour">20</span><span class="sem">3</span></div><!-- /.days --><div class="days"><span class="day">dimanche</span><span class="nday">21</span><span class="jour">21</span><span class="sem">3</span></div><!-- /.days --><div class="days"><span class="day">lundi</span><span class="nday">22</span><span class="jour">22</span><span class="sem">4</span></div><!-- /.days --><div class="days"><span class="day">mardi</span><span class="nday">23</span><span class="jour">23</span><span class="sem">4</span></div><!-- /.days --><div class="days"><span class="day">mercredi</span><span class="nday">24</span><span class="jour">24</span><span class="sem">4</span></div><!-- /.days --><div class="days"><span class="day">jeudi</span><span class="nday">25</span><span class="jour">25</span><span class="sem">4</span></div><!-- /.days --><div class="days"><span class="day">vendredi</span><span class="nday">26</span><span class="jour">26</span><span class="sem">4</span></div><!-- /.days --><div class="days"><span class="day">samedi</span><span class="nday">27</span><span class="jour">27</span><span class="sem">4</span></div><!-- /.days --><div class="days"><span class="day">dimanche</span><span class="nday">28</span><span class="jour">28</span><span class="sem">4</span></div><!-- /.days --><div class="days"><span class="day">lundi</span><span class="nday">29</span><span class="jour">29</span><span class="sem">5</span></div><!-- /.days --><div class="days"><span class="day">mardi</span><span class="nday">30</span><span class="jour">30</span><span class="sem">5</span></div><!-- /.days --><div class="days"><span class="day">mercredi</span><span class="nday">31</span><span class="jour">31</span><span class="sem">5</span></div><!-- /.days --></div><!-- /.month --><!DOCTYPE html>
<html lang="fr">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
       <title>Calendrier</title>
    <!-- Typographie -->
    <link href="https://fonts.googleapis.com/css?family=Open+Sans|Lato:300,400,700|Roboto:100,300,400,500,700" rel="stylesheet">
    <!-- Icones -->
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- Favicon -->
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">    
    <!-- Styles CSS -->
    <link rel="stylesheet" href="css/normalize.min.css">
    <link rel="stylesheet" href="css/calendrier.css">
    <!-- Scripts -->
    <script src="js/date.js"></script>
  </head>
  <body>

     <div class="container">
      <header class="header">
      <div class="header__top">
         <div class="header__top-date">
         lundi 16 avril 2018 <br>
         (Semaine: 16) (Jour  : 106) (Il reste 259 jours jusqu'à la fin de l'année)
         </div><!-- /.header__top-date -->
         <div class="header__top-titre text-center">
            <a href="/"><i class="fa fa-calendar"></i> Calendrier 2018 </a>
         </div><!-- /.header__top-titre -->
         <div class="header__top-time">
            <i class="fa fa-clock-o"></i> <span id="time"><script>window.onload=dspTime('time')</script></span>
         </div><!-- /.header__top-time -->
      </div><!-- /.header__top -->
      </header><!-- /header -->
      <nav class="nav">
         <div class="previous__year">
            <a href="http://localhost/calend/?year=2017"><Précédent></a>
         </div><!-- /.previous__year -->
         <ul class="menu">
            <li class="active"><a href="#sem1" id="sema">Semestre 1</a></li>
            <li><a href="#sem2" id="semb">Semestre 2</a></li>
            <li><a href="#feries" id="fera">Jours fériés</a></li>
         </ul><!-- /.menu -->
         <div class="next__year">
            <a href="http://localhost/calend/?year=2019"><Suivant></a>
         </div><!-- /.previous__year -->
      </nav><!-- /.nav -->
    <section id="sem1" class="section">
     <h1 class="text-center">Premier Semestre</h1>
     <hr class="hr">
     <div class="mois">
       
     </div><!-- /.mois -->
   </section><!-- /#sem1 /.section -->
   <section id="sem2" class="section">
     <h1 class="text-center">Deuxième Semestre</h1>
     <hr class="hr">
     <div class="mois">

     </div><!-- /.mois -->
   </section><!-- /#sem1 /.section -->

  
  
          <footer class="footer text-center">
          <p>© Copyright. <a href="http://localhost/calend">Calendrier 2018</a>. Tous Droits Réservés.</p>
        </footer><!-- /footer -->
      </div><!-- /.container -->
      <!-- Scripts -->
      <script src="js/jquery-3.2.1.min.js"></script>
      <script src="js/calend.js"></script>
   </body>
</html>


Il se met au début, juste avant le <!DOCTYPE html>
Si tu as une idée !
Cordialement
0