【问题标题】:Keeping HTML files separated from the PHP files (template based)将 HTML 文件与 PHP 文件分开(基于模板)
【发布时间】:2014-06-17 21:42:22
【问题描述】:

我试图将所有 PHP 文件与 HTML 文件分开。一种基于模板的项目,但没有使用任何模板引擎,因为它们大多臃肿,而且你需要学习另一种完全不是 PHP 的语言。

无论如何,我的index.php 文件中有以下代码:

<?php

$query = "SELECT id FROM products ORDER by id";

$product_list = "";
if ($stmt = mysqli_prepare($db_conx, $query)) {

    /* execute statement */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $id);

    /* fetch values */
    while (mysqli_stmt_fetch($stmt)) {
        $product_list .= "

}
}

?>
<?php include "template.php"; ?>

我的template.php 文件中有这段代码:

<html>
<head>
</head>

<body>

<div class='prod_box'>
        <div class='center_prod_box'>
          <div class='product_title'><a href='#'>$product_name</a></div>
          <div class='product_img'><a href='#'><img src='images/" . $id . "Image1.jpg' alt='' border='0' /></a></div>
          <div class='prod_price'><span class='reduce'>350$</span> <span class='price'>270$</span></div>
        </div>
        <div class='prod_details_tab'> <a href='#' class='prod_buy'>Add to Cart</a> <a href='#' class='prod_details'>Details</a> </div>
      </div>

</body>
</html>

当我运行代码时,我基本上得到了与您在上面看到的完全一样的 HTML 页面。所以 MySQL 数据库中没有显示任何数据!

编辑:

我尝试在我的while 循环中使用以下代码,但还是一样:

$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$shipping = $row["shipping"];
$category = $row["category"];

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 你在哪里定义了$product_name$product_name 也不在 php 标签之间。
  • @Daan,我想,我不需要这样做,因为我使用的是while loop。所以应该从while loop的mysql数据库中提取所有内容。
  • 与其重新发明轮子,不如看看Mustache / MustachePHP
  • @user3592614 搜索 MVC
  • @user3592614 如果不使用丝网印刷方法,您的变量内容应该如何打印在屏幕上?听起来像是对更多轮子的重新发明......说真的,你有多少(PHP)编码经验?

标签: php templates


【解决方案1】:

我建议使用模板系统来解析您的模板文件。

只是一些又快又脏的东西:

class Example {
    // This will be used to save all the variables set trough the set() function within the class as an array
    private $variables = array();

    function set($name,$value) {
                // Here we are going to put the key and value in the variables array
        $this->variables[$name] = $value;
    }

    function Template($file) {
        // First set the file path of the template, the filename comes from the Template({filename}) function.
        $file = '/templates/'.$file.'.php';

        // Here we are going to extract our array, every key will be a variable from here!
        extract($this->variables);

        // Check if it is actually a file
        if (!is_file($file)) {
            throw new Exception("$file not found");
        // Check if the file is readable
        } elseif(!is_readable($file)) {
            throw new Exception("No access to $file");
        } else {
        // if both are fine we are going to include the template file :)
            include($file);
        }
    }
}

并像这样使用它:

$class = new Example;
$class->set("data", $data);
// like passing a name:
$class->set("user", $username);
$class->Template("filename");

然后在您的模板文件中,您可以使用 $data$user 及其内容。

此外,在您的模板文件中,您没有显示变量,因为它不在 PHP 标记之间。这里有两个例子,一个是简短的,另一个是普通格式:

<?=$productname?>
// or :
<?php echo $productname; ?>

哦,你实际上什么都不做:

while (mysqli_stmt_fetch($stmt)) {
        $product_list .= "

}
}

您需要用"; 关闭开头的",并且不会向$product_list 添加任何内容。

【讨论】:

  • 对不起,这完全没有意义!
  • 这段代码只是允许 PHP 解析 HTML 文件并将变量替换为您使用 $class-> 设置的真实数据。一个基本的好例子来回答这个问题。如果@user3592614 不明白,那么他应该看一些教程来更好地理解模板是如何工作的,因为这不是 PHP 旨在开箱即用的东西。
  • @JoranDenHouting:我们能不能直接用 DEFINE 关键字来做这件事?
  • 好的,我想我们都知道谁在这里粗鲁。这是我第二次不得不移除 cmets。请停下来。
【解决方案2】:

您需要使用 PHP 中的extract() 函数来解决这个问题。然后它将作为您正在寻找的控制器 - 视图架构开始工作。

例如:

<?php

$query = "SELECT id FROM products ORDER by id";
$product_list = "";

if ($stmt = mysqli_prepare($db_conx, $query)) {

    /* execute statement */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $id);

    /* fetch values */
    while (mysqli_stmt_fetch($stmt)) {
        $product_list .= "";
    }
}

$data['product_list'] = $product_list;
$view = 'template.php';
loadTemplate($view, $data);

function loadTemplate($view, $data)
{
    extract($data);
    include($template);
}

?>

然后直接在视图部分使用$product_list。应该这样做。

工作示例:

<?php
    $data['test'] = 'This is a working example';
    $view = 'workingExampleView.php';
    loadTemplate($view,$data);

function loadTemplate($viewName,$viewData)
{
    extract($viewData);
    include($viewName);
}
?>

创建一个名为 workingExampleView.php 的新文件:

<html>
<body>
    <span><?php echo $test; ?></span>
</body>
</html>

【讨论】:

  • 这将返回一个空的$product_list... 这怎么可能是解决方案?没有冒犯性的方式:)只是好奇..
  • 缩进也可以做一些修复——你会调整吗?
  • 请详细说明你们不明白的地方。提取函数所做的是将数组的关键部分中的内容转换为单个变量,就这么简单。它只是不管来自查询的内容应该被正确地带入变量中。假设这就是 MVC 架构的工作方式。
  • @JigneshRawal MVC 是一种模式,是一组特定的约束,描述了多个应用层之间的信息流。它与模板无关。如果你认为“视图”和“模板”是同一回事,那么你对如何实现 MVC 毫无头绪。
  • @JigneshRawal 在 MVC 中,控制器将数据传递给视图。
【解决方案3】:

你的代码有点乱,你需要回到基础:你的语句返回$id,而不是你提到的$product。要从数据库中返回任何内容,请在您的 template.html 中执行以下操作:

<html>
    <body>

        <!-- More html here ... -->

        <div class='product_title'>
            <!-- Return value like this -->
            <a href='#'><?php echo $product_name; ?></a>
        </div>
    </body>
</html>

确保首先检查该值是否存在。

【讨论】:

    【解决方案4】:

    在 index.php 中

    <?php
    $query = "SELECT id FROM products ORDER by id";
    
    $product_list = "";
    if ($stmt = mysqli_prepare($db_conx, $query)) {
    
        /* execute statement */
        mysqli_stmt_execute($stmt);
    
        /* bind result variables */
        mysqli_stmt_bind_result($stmt, $id);
    
        /* fetch values */
    
    }
    
    define("PRODUCT_NAME",$row["product_name"]);
    define("PRODUCT_ID",$row["id"]);
    define("PRODUCT_PRICE",$row["price"]);
    define("PRODUCT_SHIPPING",$row["shipping"]);
    define("PRODUCT_CATEGORY",$row["category"]);
    ?>
    <?php include "template.php"; ?>
    

    在template.php中

    <html>
    <head>
    </head>
    
    <body>
    
    <div class='prod_box'>
        <div class='center_prod_box'>
          <div class='product_title'><a href='#'><?=PRODUCT_NAME?></a></div>
          <div class='product_img'><a href='#'><img src='images/<?=PRODUCT_ID?>/Image1.jpg' alt='' border='0' /></a></div>
          <div class='prod_price'><span class='reduce'>350$</span> <span class='price'>270$</span></div>
        </div>
        <div class='prod_details_tab'> <a href='#' class='prod_buy'>Add to Cart</a> <a href='#' class='prod_details'>Details</a> </div>
      </div>
    
    </body>
    </html>
    

    【讨论】:

    • 您在循环中的$product_list .= " 似乎缺少一些代码?
    • define 函数应该在 while() 函数中,同时删除 $product_list 行,你就在那里 :)
    • @JoranDenHouting:我感觉像个傻瓜,因为你的回答比我的回答好得多......谢谢你
    • 你不应该,每个人都有自己的编码风格和达到相同结果的方法。 :)
    • @VishalSharma,您如何从数据库中获取所有数据?例如:这样我们只得到 mysql 数据库中的第一项。如果我们想获取所有的项目并将它们显示在模板页面中怎么办?
    【解决方案5】:

    老实说,您应该使用模板系统。如果您不想阻碍学习它们的工作原理,有一个非常简单的方法:自己创建一个非常简单的方法。你迟早会需要它。下面的解决方案应该很简单,而且可以复制粘贴。

    这种系统的基本操作是你:

    1. 加载带有占位符字符串的模板文件。
    2. 处理模板文件(用实际值替换占位符)。
    3. 输出(或返回)带有已处理文本的 HTML。

    一个很容易理解的示例类可能是这样的:

    class HtmlPage
    {
        private $html;
    
        # Loads specified template file into $html
        public function Load($template)
        {
            if (!file_exists($template)) {
                echo "Specified template ($template) does not exist.";
                return false;
            }
    
            $this->html = file_get_contents($template);
            return true;
        }
    
        # Takes in an array of data, key is the placeholder replaced, value is the new text
        public function Process($data_array)
        {
            if (!is_array($data_array)) return;
    
            foreach ($data_array as $search => $replace)
            {
                # Add brackets so they don't have to be manually typed out when calling HtmlPage::Process()
                $search = "{$search}";
    
                $this->html = str_replace($search, $replace, $this->html);
            }
        }
    
        # Returns the page
        public function GetHtml()
        {
            return $this->html;
        }
    }
    

    可以用作:

    $page_title = "My fancy page title";
    $page_text  = "All your base are belong to us.";
    
    $page = new HtmlPage();
    
    $page->Load('html/templates/mypage.html');
    $page->Process(array(
        'TITLE' => $page_title,
        'TEXT' => $page_text
    ));
    echo $page->GetHtml();
    

    上面的代码将替换

    <html>
        <head>
            {TITLE}
        </head>
    
        <body>
            <p>{TEXT}</p>
        </body>
    </html>
    

    ...到...

    <html>
        <head>
            My fancy page title
        </head>
    
        <body>
            <p>All your base are belong to us.</p>
        </body>
    </html>
    

    在您的情况下,这将如下所示:

    html/templates/product-item.html:

    <div class='prod_box'>
        <div class='center_prod_box'>
            <div class='product_title'>
                <a href='#'>{PRODUCT_NAME}</a>
            </div>
    
            <div class='product_img'>
                <a href='#'><img src='images/{PRODUCT_ID}/Image1.jpg' alt='' border='0' /></a>
            </div>
    
            <div class='prod_price'>
                <span class='reduce'>{PRODUCT_PRICE_REDUCE}</span> <span class='price'>{PRODUCT_PRICE}</span>
            </div>
        </div>
    
        <div class='prod_details_tab'>
            <a href='#' class='prod_buy'>Add to Cart</a> <a href='#' class='prod_details'>Details</a>
        </div>
    </div>
    

    PHP 代码:

    <?php
    
    $query = "SELECT * FROM products ORDER by id";
    
    $product_list = "";
    
    if ($stmt = mysqli_prepare($db_conx, $query))
    {
        /* execute statement */
        mysqli_stmt_execute($stmt);
    
        /* bind result variables */
        mysqli_stmt_bind_result($stmt, $id);
    
        /* fetch values */
        $result = mysqli_stmt_get_result($stmt);
        while ($product = mysqli_fetch_array($result)) {
            $product_html = new HtmlPage();
            $product_html->Load('html/templates/product-list.html');
            $product_html->Process(array(
                'PRODUCT_NAME' => $product['name'];
                'PRODUCT_ID' => $product['id'];
                'PRODUCT_PRICE' => $product['price'];
                'PRODUCT_PRICE_REDUCE' => $product['price_reduce'];
            ));
            $product_list .= $product_html->GetHtml();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-19
      • 1970-01-01
      • 2014-09-27
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      相关资源
      最近更新 更多