【问题标题】:How to configure the page to search for external layout code?如何配置页面搜索外部布局代码?
【发布时间】:2012-09-29 08:34:02
【问题描述】:

我正在寻找让我的页面从外部模板页面搜索页面布局的方法。请看下面的例子。

<head>
<title></title>
</head>
<body>


<search for header, css, layout, etc from external page>

Page contents

<search for footer>


</body>

有没有办法使用 PHP 或 HTML 来做到这一点?我希望能够编辑所有页面的布局,而不必逐页进行。我欢迎任何其他方式来达到相同的效果,只要它适用于所有浏览器。

非常感谢!

【问题讨论】:

    标签: php templates layout external


    【解决方案1】:

    这正是 PHP 的用途。 PHP 脚本可以使用include 语句包含另一个脚本的内容。

    因此,您的应用程序中的每个页面都可以有一个相关的 PHP 脚本来生成内容,并在页脚布局中包含 footer.php。这样,当你更改footer.php时,所有使用它的页面都会自动获得更改。

    你不能用纯 HTML 做到这一点,但你可以用一些 javascript 和 Ajax。

    【讨论】:

      【解决方案2】:

      就像安德鲁说的,使用includes。我将设置 2 个基本示例。


      最简单的,有多个由主文件调用的布局文件:

      header.php:

      <div id="header">
          Menu can go here.
          <?php echo 'I make all my files .php, so they can use PHP functions if needed.'; ?>
      </div>
      

      页脚.php

      <div id="footer">
          <a href="#">Footer Link</a>
      </div>
      

      index.php

      <html>
          <head></head>
          <body>
              <?php include('/path/to/header.php'); ?>
              Specific index.php content here.
              <?php include('/path/to/footer.php'); ?>
          </body>
      </html>
      

      另一种选择是拥有一个 PHP 文件,其中包含函数中所有不同的布局元素。我喜欢这个的原因是因为你可以包含一个文件,然后为不同的部分调用特定的函数。这也可以用于传递变量,如页面标题。

      layout.php

      <?php
      function makeHeader($title) {
          return 'My title is: '.$title;
      }
      
      function makeFooter() {
          $html = '
              <div id="footer">
                  <a href="#">Footer Link</a>
              </div>
          ';
          return $html;
      }
      ?>
      

      index.php

      <?php include('/path/to/include.php'); ?>
      <html>
          <head></head>
          <body>
              <?php echo makeHeader('Page Title'); ?>
              Specific index.php content here.
              <?php echo makeFooter(); ?>
          </body>
      </html>
      

      只需确保在包含文件时使用相对路径 (no http://www.)。这将允许变量和函数顺利转移。最简单的方法是使用 PHP 变量 $_SERVER['DOCUMENT_ROOT'],因此如果您有一个文件 http://mysite.com/includes/layout.php,无论您包含的文件位于何处,都可以将其包含在 include($_SERVER['DOCUMENT_ROOT'].'/includes/layout.php') 中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多