Name

fetch() — 取得输出内容

说明

string fetch(string template,
string cacheid,
string compile_id);

该函数将取得一个模板输出的内容,而不是显示出来。 该函数需要指定一个合法的模板资源的类型和路径。 第二个可选的参数
$cacheid设置缓存,详情参见 缓存

As an optional third parameter, you can pass a $compile_id. This is in the event that you want to compile different versions of the same template, such as having separate templates compiled for different languages. You can also set the $compile_id variable once instead of passing this to each call to this function.


Example 14.21. fetch()

  1. <?php
  2. include('Smarty.class.php');
  3. $smarty = new Smarty;
  4.  
  5. $smarty->setCaching(true);
  6.  
  7. // 按照URL来MD5生成一个特定的缓存ID
  8. $cache_id = md5($_SERVER['REQUEST_URI']);
  9.  
  10. // 捕获输出
  11. $output = $smarty->fetch('index.tpl', $cache_id);
  12.  
  13. // 处理输出的内容
  14. echo $output;
  15. ?>
  16.  


Example 14.22. 用fetch()来发邮件

email_body.tpl模板的内容:

  1. Dear {$contact_info.name},
  2.  
  3. Welcome and thank you for signing up as a member of our user group.
  4.  
  5. Click on the link below to login with your user name
  6. of '{$contact_info.username}' so you can post in our forums.
  7.  
  8. {$login_url}
  9.  
  10. List master
  11.  
  12. {textformat wrap=40}
  13. This is some long-winded disclaimer text that would automatically get wrapped
  14. at 40 characters. This helps make the text easier to read in mail programs that
  15. do not wrap sentences for you.
  16. {/textformat}
  17.  

该PHP脚本使用了PHP的 mail()函数。

  1. <?php
  2.  
  3. // 从数据库或其他来源获取到$contact_info
  4.  
  5. $smarty->assign('contact_info',$contact_info);
  6. $smarty->assign('login_url',"http://{$_SERVER['SERVER_NAME']}/login");
  7.  
  8. mail($contact_info['email'], 'Thank You', $smarty->fetch('email_body.tpl'));
  9.  
  10. ?>
  11.  

参见 {fetch}display(), {eval}, 和 templateExists().

原文: https://www.smarty.net/docs/zh_CN/api.fetch.tpl