首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Twig PHP模板引擎构建站点

使用Twig PHP模板引擎构建站点
EN

Stack Overflow用户
提问于 2012-03-23 23:52:14
回答 1查看 8.4K关注 0票数 8

我已经通读了Twig的文档,但我不太明白如何将它们联系起来。

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

单独的页面内容存储在.phtml.html.twig文件中,这些文件可以链接到站点上的其他页面。但是,它们总是链接到另一个.php文件,而不是模板。

什么是最好的方式来抽象这个过程,以便我只需要一个php文件的多个模板?Htaccess?某种路由器类?有没有什么例子?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-03-24 04:14:36

如果你正在使用多个PHP文件,那么创建模板渲染类是明智之举,它将引导Twig类,设置选项,并负责查找和渲染请求的模板:

代码语言:javascript
复制
<?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);
  }
}

不要复制-粘贴,这只是一个例子,你的实现可能会根据你的需要而不同。将此类保存到某个位置

用法

我假设您有一个类似于下面这样的目录结构:

代码语言:javascript
复制
/home/www/index.php
/home/www/products.php
/home/www/about.php

在dir服务器的根目录下创建目录(本例中为/home/www):

代码语言:javascript
复制
/home/www/templates # this will store all template files
/home/www/cache # cached templates will reside here, caching is highly recommended

将模板文件放在templates目录下

代码语言:javascript
复制
/home/www/templates/index.twig
/home/www/templates/products.twig
/home/www/templates/blog/categories.twig # Nested template files are allowed too

现在示例index.php文件:

代码语言:javascript
复制
<?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目录的web访问(甚至将其放在外部的某个地方),否则每个人都可以下载模板文件。

票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9842342

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档