Geo*_*off 10 php foreach loops magento magento-1.5
快速查看:我想从一组特定的返回结果静态块到PHTML文件(该文件,然后从一个叫上CMS页面中)的Magento.
注意:我一直在搜索谷歌和一些答案让我比其他人更接近,但我尝试过的任何东西似乎100%工作?
细节:
我已经有一组特定的静态块,都以标识符开头testimonial-.例如,每个静块是这样的:testimonial-1,testimonial-2,testimonial-3等.我在我的开发网站上总共有5个(更多关于现场网站,但这并不重要).
我有一个带有代码的CMS页面name.phtml(文件的位置在这里:app/design/frontend/[package]/[template]/template/page /):
{{block type="core/template" template="page/name.phtml" title="Others Say:" identifier="testimonial-"}}
Run Code Online (Sandbox Code Playgroud)
这是我的.phtml文件的代码:
<?php
// add the collection with filters
$collection = Mage::getModel('cms/block')->getCollection()
->addFieldToFilter('identifier', array('like'=>'testimonial'.'%'))
->addFieldToFilter('is_active', 1);
// get the count
$blockCount = $collection->count();
echo 'Block Count: ' . $blockCount . '<br />'; // just for testing
$blockNum = 1;
foreach($collection as $key => $value){
$_blockId = $this->getIdentifier();
$block_ID = $_blockId . $blockNum;
echo "Key: " . $key . " - " . "Block ID: " . $block_ID . "<br />";
$blockNum++;
}
$_block = $this->getLayout()->createBlock('cms/block')->setBlockId($block_ID);
if ($_block) :
?>
<div class="block block-testimonial">
<div class="block-title">
<strong><?php echo $this->getTitle(); ?></strong>
</div>
<div class="block-content">
<?php echo $_block->toHtml(); ?>
</div>
Run Code Online (Sandbox Code Playgroud)
循环foreach($collection as $key => $value)打印出来:
Key: 27 - Block ID: testimonial-1
Key: 28 - Block ID: testimonial-2
Key: 29 - Block ID: testimonial-3
Key: 30 - Block ID: testimonial-4
Key: 31 - Block ID: testimonial-5
Run Code Online (Sandbox Code Playgroud)
这很好.
但是,回显的唯一块是最后一个块(testimonial-5).由于我试图列出所有的推荐块,我怎样才能将每个块ID回显到页面?
对我来说很容易,我是php的初学者.
小智 8
你不是在foreach循环中打印块.解决方案:将}括号移动到粘贴代码的末尾
$blockNum = 1;
foreach($collection as $key => $value){
$_blockId = $this->getIdentifier();
$block_ID = $_blockId . $blockNum;
echo "Key: " . $key . " - " . "Block ID: " . $block_ID . "<br />";
$blockNum++;
$_block = $this->getLayout()->createBlock('cms/block')->setBlockId($block_ID);
if ($_block) : ?>
<div class="block block-testimonial">
<div class="block-title">
<strong><?php echo $this->getTitle(); ?></strong>
</div>
<div class="block-content">
<?php echo $_block->toHtml(); ?>
</div>
<?php
endif;
}
Run Code Online (Sandbox Code Playgroud)
我认为在Magento Connect上有一些推荐模块,它们正在做你想要的工作.另一方面,如果您正在寻找"简单"的解决方案,或者您正在尝试使用Magento,这种方法是否正常.