How to use twig to create a website?

<?php
// Use correct path to Twig's autoloader file
require_once '/path/to/lib/Twig/Autoloader.php';
// Twig's autoloader will take care of loading required classes
Twig_Autoloader::register();

class TemplateRenderer
{
  public $loader; // Instance of Twig_Loader_Filesystem
  public $environment; // Instance of Twig_Environment

  public function __construct($envOptions = array(), $templateDirs = array())
  {
    // Merge default options
    // You may want to change these settings
    $envOptions += array(
      'debug' => false,
      'charset' => 'utf-8',
      'cache' => './cache', // Store cached files under cache directory
      'strict_variables' => true,
    );
    $templateDirs = array_merge(
      array('./templates'), // Base directory with all templates
    );
    $this->loader = new Twig_Loader_Filesystem($templateDirs);
    $this->environment = new Twig_Environment($this->loader, $envOptions);
  }

  public function render($templateFile, array $variables)
  {
    return $this->environment->render($templateFile, $variables);
  }
}
Don't copy-paste, this is just an example, your implementation may be different depending on your needs. Save this class somewhere
Usage. I'm going to assume that you have a directory structure similar to this:
/home/www/index.php
/home/www/products.php
/home/www/about.php

Create directories under webserver's root dir (/home/www in this case):
/home/www/templates # this will store all template files
/home/www/cache # cached templates will reside here, caching is highly recommended

Put your template files under templates directory
/home/www/templates/index.twig
/home/www/templates/products.twig
/home/www/templates/blog/categories.twig # Nested template files are allowed too

Now sample index.php file:
<?php
// Include our newly created class
require_once 'TemplateRenderer.php';

// ... some code

$news = getLatestNews(); // Pulling out some data from databases, etc
$renderer = new TemplateRenderer();
// Render template passing some variables and print it
print $renderer->render('index.twig', array('news' => $news));
Other PHP files will be similar.
Notes
Change settings/implementation to suit your needs. You may want to restrict web access to the templates directory (or even put it somewhere outside), otherwise everyone will be able to download template files.
 

你可能感兴趣的:(create)