使用Twig PHP Template Engine构建站点

8 php twig

我已经阅读了Twig的文档,但我不太明白如何连接点.

假设我创建了一个index.php实例化Twig_Loader_FilesystemTwig_Environment类的文件.我可以在这里加载一个模板loadTemplate().

个人页面内容存储在.phtml.html.twig文件,这可能链接到网站上的其他网页.但是,这些将始终链接到另一个.php文件,而不是模板.

抽象这个过程的最佳方法是什么,这样我只需要一个php文件用于多个模板?htaccess的?某种路由器类?那里有什么例子吗?

gal*_*han 16

如果你正在使用几个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);
  }
}
Run Code Online (Sandbox Code Playgroud)

不要复制粘贴,这只是一个例子,根据您的需要,您的实现可能会有所不同.在某个地方保存这个课程

用法

我将假设您有一个类似于此的目录结构:

/home/www/index.php
/home/www/products.php
/home/www/about.php
Run Code Online (Sandbox Code Playgroud)

在webserver的根目录下创建目录(/home/www在本例中):

/home/www/templates # this will store all template files
/home/www/cache # cached templates will reside here, caching is highly recommended
Run Code Online (Sandbox Code Playgroud)

将模板文件放在templates目录下

/home/www/templates/index.twig
/home/www/templates/products.twig
/home/www/templates/blog/categories.twig # Nested template files are allowed too
Run Code Online (Sandbox Code Playgroud)

现在示例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));
Run Code Online (Sandbox Code Playgroud)

其他PHP文件将类似.

笔记

更改设置/实施以满足您的需求.您可能希望限制对templates目录的Web访问(甚至将其放在外面的某个位置),否则每个人都可以下载模板文件.