Opencart 使用模型-视图-控制器框架 (MVC),其中控制器与模型对话以检索数据,准备数据,然后将其传递给视图(Opencart 中的 .tpl 文件),然后适当地显示它。
在您的情况下, header.tpl 没有 $products 数组的数据,因为它尚未在 header.php 控制器中准备好。因此,在标头控制器(catalog/controller/header.php)的 index() 函数中,让我们从模型中获取所有数据,按照我们想要的方式进行准备,然后将其传递给视图:
$this->load->model('catalog/category'); //
$this->load->model('catalog/product'); //Load our models so the controller can get data
$categories = $this->model_catalog_category->getCategories(0); //get all top level categories
$all_products = array();
foreach ($categories as $category) //go through each category and get all the products for each category
{
$category_products = $this->model_catalog_product->getProductsforCategoryId($category['category_id']); //returns product IDs for category
foreach ($category_products as $category_product)
{
$product_data = $this->model_catalog_product->getProduct($category_product); //fetch product data for this product then add it to our array of all products
$all_products[] = array(
'href' => $this->url->link('product/product', 'product_id=' . $product_data['product_id']),
'name' => $product_data['name']
);
}
}
$this->data['products'] = $all_products; //Now pass our product array data to the view, in the view this will be the $products array
这是假设您的所有产品仅属于顶级类别而不属于任何子类别。如果您将来确实创建了顶级类别的子类别,您将需要遍历这些子类别并获取每个子类别的产品。