Get Smarty

Donate

Smarty Icon

You may use the Smarty logo according to the trademark notice.

Smarty Template Engine Smarty Template Engine

For sponsorship, advertising, news or other inquiries, contact us at:

Sites Using Smarty

Buy cheap glasses from Cheapglasses123.com and save up to 80%.

Where to buy prescription glasses? EyewearCanada.com is your best choice!

Advertisement

自定义模板资源

你可以通过任何可访问的来源来提供模板,如数据库,网络sockets,文件等, 编写这些来源的资源插件并将他们注册到Smarty。

参见资源插件

Note

注意你不能覆盖内置的file:资源, 但你可以设计一个基于文件系统的资源并为其注册另一个资源名称。

Example 16.10. U使用自定义资源


<?php

/**
* MySQL 资源
*
* 过自定义API,实现用MySQL来存取模板和配置资源。
*
* 表定义:
* <pre>CREATE TABLE IF NOT EXISTS `templates` (
*   `name` varchar(100) NOT NULL,
*   `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
*   `source` text,
*   PRIMARY KEY (`name`)
* ) ENGINE=InnoDB DEFAULT CHARSET=utf8;</pre>
*
* 演示数据:
* <pre>INSERT INTO `templates` (`name`, `modified`, `source`) VALUES ('test.tpl', "2010-12-25 22:00:00", '{$x="hello world"}{$x}');</pre>
*
* @package Resource-examples
* @author Rodney Rehm
*/
class Smarty_Resource_Mysql extends Smarty_Resource_Custom {
 // PDO 实例
 protected $db;
 // prepared fetch() statement
 protected $fetch;
 // prepared fetchTimestamp() statement
 protected $mtime;

 public function __construct() {
     try {
         $this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty", "smarty");
     } catch (PDOException $e) {
         throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
     }
     $this->fetch = $this->db->prepare('SELECT modified, source FROM templates WHERE name = :name');
     $this->mtime = $this->db->prepare('SELECT modified FROM templates WHERE name = :name');
 }
 
 /**
  * 从数据库中获取一个模板内容及修改时间。
  *
  * @param string $name 模板名称
  * @param string $source 引用的模板资源
  * @param integer $mtime 引用的模板修改时间戳
  * @return void
  */
 protected function fetch($name, &$source, &$mtime)
 {
     $this->fetch->execute(array('name' => $name));
     $row = $this->fetch->fetch();
     $this->fetch->closeCursor();
     if ($row) {
         $source = $row['source'];
         $mtime = strtotime($row['modified']);
     } else {
         $source = null;
         $mtime = null;
     }
 }
 
 /**
  * 获取一个模板的修改时间
  *
  * @note 本方法是可选的。仅在修改时间的获取比加载完整的模板资源更快的情况下使用。
  * @param string $name 模板名称
  * @return integer 模板被修改的时间戳
  */
 protected function fetchTimestamp($name) {
     $this->mtime->execute(array('name' => $name));
     $mtime = $this->mtime->fetchColumn();
     $this->mtime->closeCursor();
     return strtotime($mtime);
 }
}


require_once 'libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->registerResource('mysql', new Smarty_Resource_Mysql());

// 在PHP中使用资源
$smarty->display("mysql:index.tpl");
?>

  

在模板中:


{include file='mysql:extras/navigation.tpl'}

  

Comments
No comments for this page.

Advertisement