Need to know how to install twig on your Linux Machine? Here you will see exactly how to do it.
Here at Ibmi Media, as part of our Server Management Services, we regularly help our customers to perform Linux related tasks and Installations.
In this context, we shall look into how to install Twig on a Linux Machine.
Twig is a very popular template engine for the PHP programming language. It is very flexible, fast, and secure for PHP applications.
Additionally, its syntax is easy to understand which does not require any dynamic operations in the template files.
Twig can be installed easily by means of Composer. A composer is a dependency Manager for PHP which helps to declare the dependent libraries your project needs.
Start by downloading the Composer installer to the root directory (twig) of your application by running the commands below;
cd /var/www/twig
curl -s http://getcomposer.org/installer | PHP
Now, a Composer executable file named "composer.phar" will be downloaded.
Next, you should create a file with name "composer.json" in the same directory.
To do this, run the command below;
nano composer.json
Now, add the following attributes into this file as seen below;
{
"require": {
"twig/twig": "1.*"
}
}
Now your application will be dependent on the Twig templating engine.
Next, install its dependencies by running the composer command below;
php composer.phar install
After this installation, the Twig files will be downloaded into the "vendor/Twig" folder. Next, you should connect it to the application. Edit the "app.php" file with the command below;
nano app/app.php
Next, you should remove all its contents and add the following lines at the top of the file;
<?php require_once '../vendor/autoload.php'; ?>
By means of the above line, the Composer autoloader can be loaded which works with Twig as well. Next, add the following line beneath to require the Twig autoloader;
require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();
Next, locate a Twig template file and add the following directives to it which will help to print out to your web page when loaded;
<?php $loader = new Twig_Loader_Filesystem('../views/'); ?>
<?php $twig = new Twig_Environment($loader); ?>
<?php echo $twig->render('new_page.html', array('text' => 'Hello world!')); ?>
Now, you need to create a page "new_page.html" with the command below;
nano views/new_page.html
Add the following code into the file;
<h1>{{ text }}</h1>
Then save it.
Once you load the "app.php" file on your web browser, the text above will be printed to the screen.
This article will show you how to install and configure Twig on your own Linux Machine.