【问题标题】:How to dynamically load a content in a template如何在模板中动态加载内容
【发布时间】:2014-02-06 12:13:33
【问题描述】:

我有 6 个文件。

  1. header.php
  2. footer.php
  3. home.php
  4. page1.php
  5. page2.php
  6. index.php

header.php

<html>
<head>
<title>test</title>
</head>
<body>
<div class="menu">
 <ul>
<li><a href="home.php>Home</a></li>
<li><a href="page1.php>Page 1</a></li>
<li><a href="page2.php>Page 2</a></li>
</ul>
</div>

<div class="content">

footer.php

</div>
</body>
</html>

index.php

<?php

    include "header.php";
    //content goes here
    include "home.php";  //this include must change when i click on page 1 or page 2 link    
    //content goes here
    include "footer.php";

?>

如何在点击链接时动态更改 index.php 的内容?

【问题讨论】:

  • 你为什么不创建页面并提供链接?
  • 你想用include "page1.php";替换include "home.php";是你想要的吗?如果是这样,为什么不创建链接?
  • 好吧,我只想要 index.php 来处理所有事情。我只想创建将由 index.php 加载的页面
  • 检查 Smarty smarty.net 模板引擎。也许它会帮助你。您可以将变量添加到 tmp 文件中并稍后对其进行修改,您还可以调用并包含不同的文件等。您可以对您的系统执行类似的操作,但我建议您尝试 Smarty。它为此目的而构建。

标签: php html


【解决方案1】:

主要结构:

index.php --> Layout + handles which page to display
header.php --> Included in index
footer.php --> Include in index

链接类似于index.php?page=home

index.php:

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

    <?php include 'header.php'; ?>

    <?php 

       // Handle here what page to include : 
       // - Store $_GET['page']
       // - Sanitize the var
       // - Check if you have a file that would correspond to this page
       // - Include it

    ?>

    <?php include 'footer.php'; ?>

    </body>
</html>

header.php:

<header>
    ....
</header>

页脚.php:

<footer>
 .....
</footer>

【讨论】:

  • 谢谢,这就是我要找的。​​span>
【解决方案2】:

每个 URL 都需要不同的脚本:

index.php

<?php

    include "header.php";
    //content goes here
    include "home.php";  
    //content goes here
    include "footer.php";

?>

page1.php

<?php

    include "header.php";
    //content goes here
    include "page1_content.php"; //contains contents of page1
    //content goes here
    include "footer.php";

?>

page2.php

<?php

    include "header.php";
    //content goes here
    include "page2_content.php"; //contains contents of page2
    //content goes here
    include "footer.php";

?>

【讨论】:

  • 这样做我需要创建额外的文件吗?
  • 这就像 OP 将 header 和 footer.php 放在 page2_content.php(或 home / page1_content)中一样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-25
  • 2018-09-04
  • 1970-01-01
  • 2012-07-04
  • 2012-04-29
相关资源
最近更新 更多