【问题标题】:Including template files and dynamically changing variables within them包括模板文件和其中动态变化的变量
【发布时间】:2009-12-21 18:11:03
【问题描述】:

为了让我自己的生活更轻松,我想为我的项目构建一个非常简单的模板引擎。我想到的是将 .html 文件放在一个目录中,当我需要它们时,这些文件会被包含到使用 PHP 的页面中。所以一个典型的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}

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

【问题讨论】:

    标签: php function templates


    【解决方案1】:

    为了简单起见,为什么不直接使用带有 PHP 短标签的 .php 文件而不是 {PAGE_TITLE} 等?

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

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

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

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

    【讨论】:

    • 有趣。不知道那个。感谢您的链接。
    【解决方案2】:

    为什么不直接使用 php?

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

    【讨论】:

      【解决方案3】:

      最简单的做法是这样的:

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

      【讨论】:

        【解决方案4】:

        您可能理解,PHP 本身就是一个模板引擎。话虽如此,有几个项目可以添加您所描述的模板类型。您可能想要调查的一个是Smarty Templates。您可能还想查看在SitePoint 上发布的article,它对模板引擎进行了总体描述。

        【讨论】:

          【解决方案5】:

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

          // 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>
          

          【讨论】:

            猜你喜欢
            • 2021-09-14
            • 1970-01-01
            • 2023-03-09
            • 1970-01-01
            • 2020-04-28
            • 1970-01-01
            • 2021-05-11
            • 2011-09-17
            • 2019-06-15
            相关资源
            最近更新 更多