簡體   English   中英

將HTML文件與PHP文件分開(基於模板)

[英]Keeping HTML files separated from the PHP files (template based)

我試圖將所有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循環中使用以下代碼, while仍保持不變:

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

有人可以幫我這個忙嗎?

我建議使用模板系統來解析您的模板文件。

只是一些快速而骯臟的事情:

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

老實說,您應該使用模板系統 如果您不想阻礙學習它們的工作原理,則有一個非常簡單的方法:自己創建一個非常簡單的方法。 您遲早會需要它。 下面的解決方案應該非常簡單,並且可以復制粘貼。

該系統的基本操作是:

  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();
    }
}

您的代碼有些混亂,您需要回到基礎知識:您的語句返回的是$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>

確保首先檢查該值是否存在。

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

您需要使用PHP中的extract()函數來解決此問題。 然后它將開始用作您要查找的Controller-View架構。

例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM