包括模板文件和动态更改变量

时间:2009-12-21 18:11:03

标签: php function templates

为了让自己的生活更轻松,我想为我的项目构建一个非常简单的模板引擎。我想到的是在我希望它们的目录中使用PHP包含.html文件。所以典型的index.php看起来像这样:

<?php

IncludeHeader("This is the title of the page");
IncludeBody("This is some body content");
IncludeFooter();

?>

沿着这些方向的东西,然后在我的模板文件中:

<html>
<head>
    <title>{PAGE_TITLE}</title>
</head>
<body>

但是我无法解决的一件事是将参数传递给函数并用它替换{PAGE_TITLE}

有没有人有解决方案或更好的方法来做到这一点?感谢。

5 个答案:

答案 0 :(得分:1)

为了保持简单,为什么不使用带有PHP短标签而不是{PAGE_TITLE}之类的.php文件?

<html>
<head>
    <title><?=$PAGE_TITLE?></title>
</head>
<body>

然后,为了隔离变量空间,您可以创建一个模板加载函数,其功能如下:

function load_template($path, $vars) {
    extract($vars);
    include($path);
}

其中$ vars是一个关联数组,其键等于变量名,值等于变量值。

答案 1 :(得分:1)

为什么不使用php?

<html>
<head>
    <title><?=$pageTitle; ?></title>
</head>
<body>

答案 2 :(得分:0)

最简单的事情就是这样:

<?php
function IncludeHeader($title)
{
    echo str_replace('{PAGE_TITLE}', $title, file_get_contents('header.html'));
}
?>

答案 3 :(得分:0)

正如您所理解的,PHP本身就是一个模板引擎。话虽这么说,有几个项目添加了你描述的模板类型。您可能想要调查的是Smarty Templates。您可能还想查看article发布的SitePoint一般情况下的模板引擎。

答案 4 :(得分:0)

这是我看到一些框架使用的技巧:

// Your function call
myTemplate('header',
    array('pageTitle' => 'My Favorite Page',
          'email' => 'joe@bob.com',
    )
);

// the function
function myTemplate($filename, $variables) {
    extract($variables);
    include($filename);
}

// the template:
<html>
<head>
    <title><?=$pageTitle?></title>
</head>
<body>
    Email me here<a href="mailto:<?=$email?>"><?=$email?></a>
</body>
</html>