使用没有Smarty的fetch()?

时间:2014-01-16 08:00:25

标签: php smarty

Smarty 3可以选择设置(分配)变量,然后将文件包含(获取)到新变量。
没有Smarty课,我怎么能这样做呢? file_get_contents不起作用,还有其他什么吗?

例如,这是Smarty代码:

<?php
$variable = 'Hello World';
$smarty->assign('variable', $variable);
$content = $smarty->fetch('content.tpl'); // content.tpl have "{$variable}" inside
echo '<script>document.write("' . $content . '")</script>'; // this will output <script>document.write("Hello World")</script>
?>

我想在没有Smarty的情况下这样做:

<?php
$variable = 'Hello World';
$content = file_get_contents('content.php'); // content.php have "echo $variable;" inside
echo '<script>document.write("' . $content . '")</script>';// this needs to output <script>document.write("Hello World")</script>, but it's outputing echo $variable;
?>

1 个答案:

答案 0 :(得分:0)

你可以利用缓冲技巧。

function fetch($filename, array $vars) {

   ob_start(); // Start output buffering

   extract($vars); // Extract variables

   require($filename); // Include a file

   return ob_get_clean(); // Pass variables to included filename and return output as a string
}

然后你可以像这样使用它:

$content = fetch('content.php', array(
  'variable' => 'Hello World',
  'name'     => 'John Doe',
 ));

echo $content;

我的content.php如下所示:

<div>
  <b><?php echo $variable; ?></b>, you're logged in as <?php echo $name; ?>
</div>

输出Hello World,您以John Doe身份登录