Can I use twig in standalone project

php, twig

Solution

I found this Sitepoint tutorial very straightforward. I've simplified and summarised the steps:

It assumes basic command line and Composer knowledge.

install Twig - Composer is probably the simplest way for most people. Run `composer require twig/twig` in your docroot. This will create a `composer.json` and `composer.lock` if you don't already have them, and a `vendor` directory into which Composer will download Twig and a couple of the Symfony dependencies it uses. Composer will also generate some autoload files.

create a `templates` directory for your Twig source files (personally I like to put this above the docroot for security)

- create a sample `index.html.twig` template in that directory

- create a `bootstrap.php` file (a few lines of PHP to load and initialise Twig (and tells it where to find the templates)

- create an `index.php` file to demonstate loading and parsing a template. This:

- loads the bootstrap

- defines some data (in an array) to populate tags in the template

- uses the Twig render() method, specifying the template and the data array

Visit the second PHP file in your browser and you should get a rendered Twig template.

boostrap.php:

<?php

// Load our autoloader
require_once __DIR__.'/vendor/autoload.php';

// Specify our Twig templates location
$loader = new Twig_Loader_Filesystem(__DIR__.'/../templates');

// Instantiate our Twig
$twig = new Twig_Environment($loader);

index.php:

<?php

require_once __DIR__.'/bootstrap.php';

// Sample data
$foo = [
  [ 'name'          => 'Alice' ],
  [ 'name'          => 'Bob' ],
  [ 'name'          => 'Eve' ],
];

// Render our view
echo $twig->render('index.html', ['foo' => $foo] );

templates/index.html.twig:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Twig Example</title>
</head>
<body>

    <ul>
    {% for item in foo %}
        <li>{{ item.name }}</li>
    {% endfor %}
    </ul>

</body>
</html>

The next stage would be to modify your index.php into a proper 'front controller' so it can handle multiple templates.

The tutorial also mentions things like caching the generated templates.

Problem

Can I use twig templating engine in a standalone project , for example to design more on 1000 html page , ie site full with static pages , if you had any simple example i will thank you

Original source