Если вы используете несколько файлов PHP, то разумно создать класс рендерера шаблонов, который будет загружать классы Twig, устанавливать параметры и заботиться о поиске и рендеринге запрошенных шаблонов:
<?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
$templateDirs
);
$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);
}
}
Не копируйте-вставьте, это всего лишь пример, ваша реализация может отличаться в зависимости от ваших потребностей. Сохраните этот класс где-нибудь
Использование
Я предполагаю, что у вас есть структура каталогов, подобная этой:
/home/www/index.php
/home/www/products.php
/home/www/about.php
Создание каталогов под корневым каталогом веб-сервера (в данном случае /home/www
):
/home/www/templates # this will store all template files
/home/www/cache # cached templates will reside here, caching is highly recommended
Поместите файлы вашего шаблона в templates
каталог
/home/www/templates/index.twig
/home/www/templates/products.twig
/home/www/templates/blog/categories.twig # Nested template files are allowed too
Теперь пример файла index.php:
<?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));
Другие файлы PHP будут похожи.
Примечания
Измените настройки / реализацию в соответствии с вашими потребностями. Возможно, вы захотите ограничить веб-доступ к каталогу templates
(или даже поместить его где-нибудь снаружи), иначе каждый сможет загрузить файлы шаблонов.