Difference between revisions of "PHP115"

From mi-linux
Jump to navigationJump to search
 
(9 intermediate revisions by 2 users not shown)
Line 6: Line 6:
  
 
There are many PHP template engines out there, there are some of the most popular ones:
 
There are many PHP template engines out there, there are some of the most popular ones:
* [http://twig.sensiolabs.org/ Twig] - probably the best current, framework-independent template engine.
+
* [https://twig.symfony.com/ Twig] - probably the best current, framework-independent template engine.
 
* [https://mustache.github.io/ Mustache] - also very popular, but very simple and so not suitable for more complex projects.
 
* [https://mustache.github.io/ Mustache] - also very popular, but very simple and so not suitable for more complex projects.
* [http://www.smarty.net/ Smarty] - very old, and the website looks very dated, but the product itself is very good and still actively maintained!
+
* [https://www.smarty.net/ Smarty] - very old, and the website looks very dated, but the product itself is very good and still actively maintained!
* [https://laravel.com/docs/5.1/blade Blade ] - Blade comes with Laravel, a very popular PHP framework, and cannot easily be used without Laravel.
+
* [https://laravel.com/docs/10.x/blade Blade ] - Blade comes with Laravel, a very popular PHP framework, and cannot easily be used without Laravel.
* [https://docs.phalconphp.com/en/latest/reference/volt.html Volt] - Volt is packaged with the Phalcon PHP framework, but can be used as a standalone product.
 
 
 
Here is an interesting [http://www.sitecrafting.com/blog/top-5-php-template-engines/ comparison] of the template engines above.
 
  
 
In this tutorial we will look at Twig
 
In this tutorial we will look at Twig
Line 18: Line 15:
 
== Installing Twig ==
 
== Installing Twig ==
  
Please read the [http://twig.sensiolabs.org/doc/installation.html installation notes] on the official website.
+
Please read the [https://twig.symfony.com/doc/3.x/installation.html installation notes] on the official website.
  
 
== Simple example==
 
== Simple example==
Line 24: Line 21:
 
First let's look at a simple example that passes variables to a template.
 
First let's look at a simple example that passes variables to a template.
  
===The template - index.html ===
+
===The template - template.html ===
  
 
<pre>
 
<pre>
Line 71: Line 68:
 
<?php
 
<?php
  
require_once 'Twig/Autoloader.php';
+
// Point to library
Twig_Autoloader::register();
+
require_once '../../vendor/autoload.php';
 
 
// Create loader object, pointing to templates folder
 
$loader = new Twig_Loader_Filesystem('templates');
 
 
 
// Set-up environment with cache (faster)
 
/*$twig = new Twig_Environment($loader, array(
 
    'cache' => 'compilation_cache',
 
));*/
 
  
// set-up environment without cache (for development)  
+
// Set up Environment
$twig = new Twig_Environment($loader);
+
$loader = new \Twig\Loader\FilesystemLoader('.');
 +
$twig = new \Twig\Environment($loader);
  
 
// Array of data
 
// Array of data
Line 92: Line 82:
  
 
// Load and render template
 
// Load and render template
echo $twig->render('index.html',  
+
echo $twig->render('template.html',  
 
                   array('a_variable' => 'Alix',  
 
                   array('a_variable' => 'Alix',  
 
                         'another_variable' => 'Bergeret',
 
                         'another_variable' => 'Bergeret',
 
                         'people' => $people));
 
                         'people' => $people));
 
 
 
?>
 
 
</pre>
 
</pre>
  
The result: [http://mi-linux.wlv.ac.uk/~in9352/twig/ http://mi-linux.wlv.ac.uk/~in9352/twig/]
+
The result: [https://mi-linux.wlv.ac.uk/~in9352/twig/workbook/ https://mi-linux.wlv.ac.uk/~in9352/twig/workbook/]
  
 
Let's look at the file above in more detail:
 
Let's look at the file above in more detail:
  
 
<pre>
 
<pre>
require_once 'Twig/Autoloader.php';
+
// Point to library
Twig_Autoloader::register();
+
require_once '../../vendor/autoload.php';
 
 
// Create loader object, pointing to templates folder
 
$loader = new Twig_Loader_Filesystem('templates');
 
  
// set-up environment without cache (for development)  
+
// Set up Environment
$twig = new Twig_Environment($loader);
+
$loader = new \Twig\Loader\FilesystemLoader('.');
 +
$twig = new \Twig\Environment($loader);
 
</pre>
 
</pre>
  
The above essentially "sets up" Twig. You specify where your templates folder is, and create a new environment to work with.
+
The above essentially "sets up" Twig:
 
+
* You specify where Twig is installed (via require_once). This might be different depending on where you have installed it.
'''Note''': During development it is best NOT to use caching, as you would not see your changes when updating a templates. Only enable caching once the website is finished and deployed.
+
* You specify where your templates folder is (in this case the current folder, aka ".", but you could put your templates in a sub-folder).
 +
* You create a new environment to work with. '''Note''': During development it is best NOT to use caching, as you would not see your changes when updating a templates. Only enable caching once the website is finished and deployed.
  
 
<pre>
 
<pre>
 
// Load and render template
 
// Load and render template
echo $twig->render('index.html',  
+
echo $twig->render('template.html',  
 
                   array('a_variable' => 'Alix',  
 
                   array('a_variable' => 'Alix',  
 
                         'another_variable' => 'Bergeret',
 
                         'another_variable' => 'Bergeret',
Line 130: Line 115:
  
 
The above renders the page. It takes 2 parameters:
 
The above renders the page. It takes 2 parameters:
* The template you wish to use (in this case "index.html" - as defined above)
+
* The template you wish to use (in this case "templs.html" - as defined above)
 
* The data you wish to pass to the template, as an array. In this case 2 string values ("Alix" and "Bergeret") and an array called $people (defined just before the render command).
 
* The data you wish to pass to the template, as an array. In this case 2 string values ("Alix" and "Bergeret") and an array called $people (defined just before the render command).
  
 
== Database example ==
 
== Database example ==
  
Let's revisit our [[PHP111|pets database example]], but this time we can separate logic from HTML.
+
Let's revisit our videogames example from the lecture, but this time we can separate logic from HTML.
  
=== The template - pets.html ===
+
=== The template - games.html ===
  
The template itself is quite simple, and very similar to the "simple example" above. Note how we loop through an array of pets (the array is called "results").
+
The template itself is quite simple, and very similar to the "simple example" above. Note how we loop through an array of games (the array is called "results").
  
 
<pre>
 
<pre>
Line 145: Line 130:
 
<html>
 
<html>
 
     <head>
 
     <head>
         <title>My pets</title>
+
         <title>My games</title>
 
     </head>
 
     </head>
 
     <body>
 
     <body>
         <h1>My pets webpage</h1>
+
         <h1>My games webpage</h1>
 
          
 
          
 
         {{ include('navigation.html') }}
 
         {{ include('navigation.html') }}
Line 157: Line 142:
 
         {% for item in results %}
 
         {% for item in results %}
 
           <tr>
 
           <tr>
             <td>{{ item.name }}</td>
+
             <td>{{ item.game_name }}</td>
             <td>{{ item.species }}</td>
+
             <td>{{ item.released_date }}</td>
 
           </tr>
 
           </tr>
 
         {% endfor %}         
 
         {% endfor %}         
Line 167: Line 152:
 
</pre>
 
</pre>
  
=== The main file - pets.php ===
+
=== The main file - games.php ===
 +
 
 +
Again, very similar to the example above. Note how we pass the whole MySQL data result object straight to the template.
  
 
<pre>
 
<pre>
 
<?php
 
<?php
 +
 +
// Point to library
 +
require_once '../../vendor/autoload.php';
 +
 +
// Set up Environment
 +
$loader = new \Twig\Loader\FilesystemLoader('.');
 +
$twig = new \Twig\Environment($loader);
  
 
// set-up environment without cache (for development)  
 
// set-up environment without cache (for development)  
// Connect to server/database
+
include("db.php");
  
 
// Run SQL query
 
// Run SQL query
$res = mysqli_query($mysqli, "SELECT name, species, age FROM pet");
+
$sql = "SELECT * FROM videogames ORDER BY released_date";
 +
$results = mysqli_query($mysqli, $sql);
  
 
// How many rows were returned?
 
// How many rows were returned?
$num_rows = mysqli_num_rows($res);
+
$num_rows = mysqli_num_rows($results);
 
 
// Loop through resultset and put in array
 
while($row = mysqli_fetch_assoc($res)) {
 
  $results[] = $row;
 
}
 
  
 
// Load and render template
 
// Load and render template
echo $twig->render('pets.html',  
+
echo $twig->render('games.html',  
 
                   array('num_rows' => $num_rows, 'results' => $results));
 
                   array('num_rows' => $num_rows, 'results' => $results));
  
Line 194: Line 184:
 
</pre>
 
</pre>
  
Most of the above should be familiar by now. The only tricky part is:
+
Result: [https://mi-linux.wlv.ac.uk/~in9352/twig/workbook/games.php https://mi-linux.wlv.ac.uk/~in9352/twig/workbook/games.php]
 
 
<pre>
 
// Loop through resultset and put in array
 
while($row = mysqli_fetch_assoc($res)) {
 
  $results[] = $row;
 
}
 
</pre>
 
 
 
We simply loop through the database resultset ($res), and insert each record in an array ($results). Then we can pass the array to the template on the next line:
 
 
 
<pre>
 
echo $twig->render('pets.html',
 
                  array('num_rows' => $num_rows, 'results' => $results));
 
</pre>
 
  
Result: [http://mi-linux.wlv.ac.uk/~in9352/twig/pets.php http://mi-linux.wlv.ac.uk/~in9352/twig/pets.php]
+
==Ready to move on?==
 +
Okay [[PHPAJAX|next topic]]!

Latest revision as of 14:34, 12 September 2023

Main Page >> Web Application Development >> Workbook >> Template Engines

Please note that this is an advanced topic. Make sure that you have worked through all the previous sections of this workbook before proceeding.

Template engines

There are many PHP template engines out there, there are some of the most popular ones:

  • Twig - probably the best current, framework-independent template engine.
  • Mustache - also very popular, but very simple and so not suitable for more complex projects.
  • Smarty - very old, and the website looks very dated, but the product itself is very good and still actively maintained!
  • Blade - Blade comes with Laravel, a very popular PHP framework, and cannot easily be used without Laravel.

In this tutorial we will look at Twig

Installing Twig

Please read the installation notes on the official website.

Simple example

First let's look at a simple example that passes variables to a template.

The template - template.html

<!DOCTYPE html>
<html>
    <head>
        <title>My first template</title>
    </head>
    <body>
        <h1>My Webpage</h1>
        
        {{ include('navigation.html') }}
        
        <p>{{ a_variable }}</p>
        <p>{{ another_variable|upper }}</p>
        
        <ul>
        {% for item in people %}
            <li>{{ item.FirstName }} {{ item.Surname }}</li>
        {% endfor %}        
        </ul>
        
    </body>
</html>

Things to note:

  • You can increase code reuse by including templates within template, in this case: include('navigation.html')
  • a_variable displays a simple variable.
  • another_variable|upper displays another variable, but converts it to uppercase. This is done using the "upper" extension.
  • for item in people allows you to loop through an array of items.

The navigation.html template, included in the file above, is fairly simple:

<ul id="navigation">
  <li><a href="#">Page 1</a></li>
  <li><a href="#">Page 2</a></li>
  <li><a href="#">Page 3</a></li>
</ul>

The home file - index.php

<?php

// Point to library
require_once '../../vendor/autoload.php';

// Set up Environment
$loader = new \Twig\Loader\FilesystemLoader('.');
$twig = new \Twig\Environment($loader);

// Array of data
$people[0]['FirstName'] = "Alix";
$people[0]['Surname'] = "Bergeret";
$people[1]['FirstName'] = "Chris";
$people[1]['Surname'] = "Dennett";

// Load and render template
echo $twig->render('template.html', 
                   array('a_variable' => 'Alix', 
                         'another_variable' => 'Bergeret',
                         'people' => $people));

The result: https://mi-linux.wlv.ac.uk/~in9352/twig/workbook/

Let's look at the file above in more detail:

// Point to library
require_once '../../vendor/autoload.php';

// Set up Environment
$loader = new \Twig\Loader\FilesystemLoader('.');
$twig = new \Twig\Environment($loader);

The above essentially "sets up" Twig:

  • You specify where Twig is installed (via require_once). This might be different depending on where you have installed it.
  • You specify where your templates folder is (in this case the current folder, aka ".", but you could put your templates in a sub-folder).
  • You create a new environment to work with. Note: During development it is best NOT to use caching, as you would not see your changes when updating a templates. Only enable caching once the website is finished and deployed.
// Load and render template
echo $twig->render('template.html', 
                   array('a_variable' => 'Alix', 
                         'another_variable' => 'Bergeret',
                         'people' => $people));

The above renders the page. It takes 2 parameters:

  • The template you wish to use (in this case "templs.html" - as defined above)
  • The data you wish to pass to the template, as an array. In this case 2 string values ("Alix" and "Bergeret") and an array called $people (defined just before the render command).

Database example

Let's revisit our videogames example from the lecture, but this time we can separate logic from HTML.

The template - games.html

The template itself is quite simple, and very similar to the "simple example" above. Note how we loop through an array of games (the array is called "results").

<!DOCTYPE html>
<html>
    <head>
        <title>My games</title>
    </head>
    <body>
        <h1>My games webpage</h1>
        
        {{ include('navigation.html') }}
        
        <p>{{ num_rows }} record(s) were returned...</p>
        
        <table border=1>
        {% for item in results %}
          <tr>
            <td>{{ item.game_name }}</td>
            <td>{{ item.released_date }}</td>
          </tr>
        {% endfor %}        
        </table>        
        
    </body>
</html>

The main file - games.php

Again, very similar to the example above. Note how we pass the whole MySQL data result object straight to the template.

<?php

// Point to library
require_once '../../vendor/autoload.php';

// Set up Environment
$loader = new \Twig\Loader\FilesystemLoader('.');
$twig = new \Twig\Environment($loader);

// set-up environment without cache (for development) 
include("db.php");

// Run SQL query
$sql = "SELECT * FROM videogames ORDER BY released_date";
$results = mysqli_query($mysqli, $sql);

// How many rows were returned?
$num_rows = mysqli_num_rows($results);

// Load and render template
echo $twig->render('games.html', 
                   array('num_rows' => $num_rows, 'results' => $results));


?>

Result: https://mi-linux.wlv.ac.uk/~in9352/twig/workbook/games.php

Ready to move on?

Okay next topic!