php Magento 使用产品集合在模板中调用 .phtml 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22266215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:46:25  来源:igfitidea点击:

Magento call a .phtml file in template with product collection

phpmagentoobject

提问by Martin

I can call a .phtml file to my .phtml template like a list.phtml.

我可以像 list.phtml 一样调用 .phtml 文件到我的 .phtml 模板。

<?php 
  echo $this->getLayout()->createBlock('core/template')->setTemplate('goodtest/test.phtml')->toHtml();
?>

But in test.phtml i cannot call $_product values.

但是在 test.phtml 中我不能调用 $_product 值。

For example:

例如:

<?php 
$_productCollection=$this->getLoadedProductCollection();
foreach ($_productCollection as $_product): 
?>

works

作品

<?php echo $_product->getName() ?>

not works:

不起作用:

<?php 
      echo $this->getLayout()->createBlock('core/template')->setTemplate('goodtest/test.phtml')->toHtml();
    ?>

In the file: test.html: <?php echo $_product->getName() ?>.

在文件中: test.html: <?php echo $_product->getName() ?>

Do I must load full collection in product again in each included file, how can i get $_product values in test.phtml most effective way?

我是否必须在每个包含的文件中再次加载产品中的完整集合,如何以最有效的方式在 test.phtml 中获取 $_product 值?

采纳答案by Mohit Kumar Arora

There are two options:

有两种选择:

  1. You can load product by Mage::getModel('catalog/product')->load(<product_id>)with id each time within foreach loop.

  2. Use below

  1. 您可以Mage::getModel('catalog/product')->load(<product_id>)在 foreach 循环中每次使用 id加载产品。

  2. 下面使用

echo $this->getLayout()->createBlock('catalog/product_list')->setTemplate('goodtest/test.phtml')->toHtml();

echo $this->getLayout()->createBlock('catalog/product_list')->setTemplate('goodtest/test.phtml')->toHtml();

instead of

代替

echo $this->getLayout()->createBlock('core/template')->setTemplate('goodtest/test.phtml')->toHtml();

echo $this->getLayout()->createBlock('core/template')->setTemplate('goodtest/test.phtml')->toHtml();

回答by raheem.unr

You can assign template through controller like @example

您可以通过控制器分配模板,如@example

$this->loadLayout();
$listBlock = $this->getLayout()->createBlock('catalog/product_list')
            ->setTemplate('catalog/product/list.phtml')
            ->setCollection($collection);

    $this->getLayout()->getBlock('content')->append($listBlock);
    $this->renderLayout();