fetch()

fetch() -- 返回模板输出

描述

string fetch ( string template [, string cache_id [, string $compile_id]])

    该函数返回一个模板的输出而不是显示它。要提供一个合法的模板资源类型和路径。作为可选的第二个参数,你可以传递一个$cache_id,参见缓存以获得更多信息。

    作为可选的第三个参数,你可以传递$compile_id。此时你可能想为同一模板编译不同的版本,例如不同的语种编译不同的版本。使用$compile_id的另一种情况是,你有多个$template_dir但是只有一个$compile_dir。对于每个$template_dir设置不同的$compile_id,否则同名的模板将会互相覆盖。你也可以一次性设置$compile_id变量,而不用每次调用该函数的时候都传递。

例子13-1. fetch()

<?php
include('Smarty.class.php');
$smarty = new Smarty;

$smarty->caching true;

// 只有不存在缓存时才进行db调用
if(!$smarty->is_cached('index.tpl')) {

  
// 随便填一些数据
  
$address '245 N 50th';
  
$db_data = array(
               
'City' => 'Lincoln',
               
'State' => 'Nebraska',
               
'Zip' => '68502'
             
);

  
$smarty->assign('Name','Fred');
  
$smarty->assign('Address',$address);
  
$smarty->assign($db_data);

}

// 捕获输出
$output $smarty->fetch('index.tpl');

// 对$output进行一些处理
echo $output;
?>

例子13-2. 使用fetch()来发送邮件

    模板email_body.tpl

Dear {$contact.name},

Welcome and thankyou for signing up as a member of our user group,

Click on the link below to login with your user name of '{$contact.login_id}'
so you can post in our forums.

http://{$smarty.server.SERVER_NAME}/login/

List master
Some user group

{include file='email_disclaimer.tpl'}

    而email_disclaimer.tpl模板使用了{textformat}修饰符:

{textformat wrap=40}
Unless you are named "{$contact.name}", you may read only the "odd numbered
words" (every other word beginning with the first) of the message above. If you have
violated that, then you hereby owe the sender 10 GBP for each even
numbered word you have read
{/textformat}

    PHP脚本中使用了PHP的mail()函数:

<?php

// 从数据库中获得联系人信息
$query  'select name, email, login_id from contacts where contact_id='.$contact_id;
$contact $db->getRow($sql);
$smarty->assign('contact'$contact);

mail($contact['email'], 'Subject'$smarty->fetch('email_body.tpl'));

?>

    参见{fetch}display(){eval}以及template_exists()