首页 > 解决方案 > 使用逻辑和 html 分离从数据库中列出帖子

问题描述

我想知道如果从数据库中列出帖子,是否有一种方法可以完全分离逻辑和 HTML(没有用于实践和学习目的的 OOP 或模板引擎),目前,代码如下所示:

<!--TEMPLATE:-->
<?php require_once(HEAD); ?>
  <body>  
    <?php require_once(HEADER); ?>
    <?php require_once(BANNER); ?>
    <!-- Main Content (S) -->
      <main class="container">
      
      <?php while($row = mysql_fetch_assoc($result)): ?>
      
      $postImg = $row["post_img"];
      $postAuthor = $row["post_author"];
      $postTitle = $row["post_title"];

      <div class="col">
        <div class="card shadow-sm">
          <img class="card-img-top" src="<?= $postImg ?>" alt="Card image cap">
          <div class="card-body">
            <p class="card-text">
              <small class="text-muted"><a class="fw-bold" href=""><?= $postAuthor ?></a></small>
            </p>
            <h5 class="card-title mb-3"><?= $postTitle ?></h5>
            <div class="d-flex justify-content-between">
            </div>
          </div>
        </div>
      </div>

      <?php endwhile; ?>

      </main>
     <!-- Main Content (E) -->
    <?php require_once(FOOTER); ?>
    <?php require_once(JS_FILES); ?>
  </body>
  </html>

变量:$postImg, $postAuthor,$postTitle使用数据库中的数据设置。目前,列出帖子的逻辑与HTML帖子模板发生在同一个地方,我有一个想法,我将这个帖子HTML移动到不同的模板文件,并listPosts()通过在循环的每次迭代中包含它来在函数中使用它。

主要问题:有没有办法将这篇文章的 HTML 代码留在当前文件中,并以某种方式将其与所有结果集行一起循环?

标签: php

解决方案


当前的方法是一种很好的做法,因为这就是人们通常将 PHP 与 HTML 结合使用的方式。

您有四个选择:

  • 要么遵循 MVC 架构模式
  • 使用模板引擎
  • 仅将您的 HTML 保存在单独php的文件中并包含在逻辑文件中。
  • 您的php文件具有逻辑,但响应是从客户端提供给 AJAX 调用的,该调用将基于数据(例如:JSON)进行渲染部分。

第三个选项的示例:

您的数据库查询脚本文件:post.php

<!--TEMPLATE:-->
<?php require_once(HEAD); ?>
  <body>  
    <?php require_once(HEADER); ?>
    <?php require_once(BANNER); ?>
    <!-- Main Content (S) -->
      <main class="container">
      
      <?php while($row = mysql_fetch_assoc($result)): ?>
      
      $postImg = $row["post_img"];
      $postAuthor = $row["post_author"];
      $postTitle = $row["post_title"];

      // include template
      include 'postView.php';
    
      <?php endwhile; ?>

      </main>
     <!-- Main Content (E) -->
    <?php require_once(FOOTER); ?>
    <?php require_once(JS_FILES); ?>
  </body>
  </html>

你的 html 文件:postView.php

<div class="col">
 <div class="card shadow-sm">
  <img class="card-img-top" src="<?= $postImg ?>" alt="Card image cap">
   <div class="card-body">
    <p class="card-text">
     <small class="text-muted"><a class="fw-bold" href=""><?= $postAuthor ?></a></small>
    </p>
    <h5 class="card-title mb-3"><?= $postTitle ?></h5>
    <div class="d-flex justify-content-between"></div>
   </div>
  </div>
</div>

推荐阅读