Difference between revisions of "PHP115"

From mi-linux
Jump to navigationJump to search
 
(40 intermediate revisions by 2 users not shown)
Line 1: Line 1:
[[Main Page]] >> [[CP2228|Web Application Development]] >> [[PHP|Workbook]] >> Smarty Template Engine
+
[[Main Page]] >> [[CP2228|Web Application Development]] >> [[PHP|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.'''
 
'''Please note that this is an advanced topic. Make sure that you have worked through all the previous sections of this workbook before proceeding.'''
  
The tutorial on Smarty's [http://www.smarty.net/ official website] are rather good, so let's just go through them:
+
= Template engines =
*[http://www.smarty.net/quick_install Quick install]
 
*[http://www.smarty.net/crash_course Crash course]
 
  
 +
There are many PHP template engines out there, there are some of the most popular ones:
 +
* [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://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/10.x/blade Blade ] - Blade comes with Laravel, a very popular PHP framework, and cannot easily be used without Laravel.
  
== Database example ==
+
In this tutorial we will look at Twig
  
I have created a simple database + Smarty example on mi-linux, here:
+
== Installing Twig ==
  
*[http://mi-linux.wlv.ac.uk/~in9352/smarty/db.php http://mi-linux.wlv.ac.uk/~in9352/smarty/db.php]
+
Please read the [https://twig.symfony.com/doc/3.x/installation.html installation notes] on the official website.
  
And here is the code for it:
+
== Simple example==
  
===The PHP files===
+
First let's look at a simple example that passes variables to a template.
  
The main file:
+
===The template - template.html ===
  
 
<pre>
 
<pre>
<?php
+
<!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>
 +
</pre>
 +
 
 +
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:
  
  // Set-up Smarty folders and connect to db
+
<pre>
  require("setup_smarty.php");
+
<ul id="navigation">
   require("connect_db.php");
+
   <li><a href="#">Page 1</a></li>
+
   <li><a href="#">Page 2</a></li>
  // Get data
+
   <li><a href="#">Page 3</a></li>
   $sql = "SELECT FilmNumber, FilmName, FilmGenre, FilmDuration FROM Films";
+
</ul>
  $myresult = mysql_query($sql);
 
  $total = mysql_num_rows($myresult);
 
 
 
  // Put data in array
 
   while ($row = mysql_fetch_assoc($myresult))
 
    $results[] = $row; 
 
 
 
  // Assign data to template
 
  $smarty->assign('total', $total);
 
  $smarty->assign('results', $results);
 
 
 
  // Display template
 
  $smarty->display('db.tpl');
 
   
 
?>
 
 
</pre>
 
</pre>
  
As you can see it includes a couple of files:
+
=== The home file - index.php ===
*setup_smarty.php: Smarty set-up
 
*connect_db.php: connection to your database
 
  
 
<pre>
 
<pre>
 
<?php
 
<?php
  // setup_smarty.php
 
  
  // Include Smarty.class.php
+
// Point to library
  require('libs/Smarty.class.php');
+
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));
 +
</pre>
  
  // Create Smarty object
+
The result: [https://mi-linux.wlv.ac.uk/~in9352/twig/workbook/ https://mi-linux.wlv.ac.uk/~in9352/twig/workbook/]
  $smarty = new Smarty();
 
  
  // Set-up Smarty folders
+
Let's look at the file above in more detail:
  $smarty->template_dir = 'templates';
+
 
  $smarty->compile_dir = 'templates_c';
+
<pre>
  $smarty->cache_dir = 'cache';
+
// Point to library
  $smarty->config_dir = 'configs';
+
require_once '../../vendor/autoload.php';
?>
+
 
 +
// Set up Environment
 +
$loader = new \Twig\Loader\FilesystemLoader('.');
 +
$twig = new \Twig\Environment($loader);
 
</pre>
 
</pre>
 +
 +
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.
  
 
<pre>
 
<pre>
<?php
+
// Load and render template
  //connect_db.php
+
echo $twig->render('template.html',
 +
                  array('a_variable' => 'Alix',
 +
                        'another_variable' => 'Bergeret',
 +
                        'people' => $people));
 +
</pre>
 +
 
 +
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").
  
  // Connect to db
+
<pre>
  $dbServer=mysql_connect("localhost","xxxx","xxxx");
+
<!DOCTYPE html>
  if (!$dbServer) {echo "Failed to connect to MySQL"; exit; }
+
<html>
  mysql_select_db("xxxx",$dbServer);
+
    <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>
 
</pre>
 
</pre>
  
===The templates===
+
=== 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>
{include file="header.tpl" title="Smarty rocks!"}
+
<?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);
  
<h1>Database example</h1>
+
// How many rows were returned?
 +
$num_rows = mysqli_num_rows($results);
  
<p>Displaying {$total} records :</p>
+
// Load and render template
 +
echo $twig->render('games.html',
 +
                  array('num_rows' => $num_rows, 'results' => $results));
  
<table style="width:200px">
 
{section name=nr loop=$results}
 
    <tr style="background-color:{cycle values="#eeeeee,#dddddd"}">
 
      <td>{$results[nr].FilmName}</td>
 
      <td>{$results[nr].FilmGenre}</td>
 
    </tr>
 
{sectionelse}
 
  <tr><td>No results found!</td></tr>
 
{/section}
 
<table>
 
  
{include file="footer.tpl"}
+
?>
 
</pre>
 
</pre>
 +
 +
Result: [https://mi-linux.wlv.ac.uk/~in9352/twig/workbook/games.php https://mi-linux.wlv.ac.uk/~in9352/twig/workbook/games.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!