Magento如果属性值为x或y,则显示自定义块

托比亚斯·宾迪莫(Tobias Bindemo)

在view.phtml上,如果属性平台的值为“ xbox”,“ playstation”或“ nintendo”,我试图获取自定义块“ console”来显示。

我得到了适用于xbox的代码,但是如何解决该问题,以便将块显示为值而不是playstation或nintendo?

Br,托比亚斯

<?php if ($_product->getAttributeText('platform') == "xbox"): ?>
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('console')->toHtml() ?><?php endif; ?>
马拉奇

您是说要为任何控制台使用相同的块吗?我建议一个转换声明

用以下代码替换您编写的if语句:

switch($_product->getAttributeText('platform')){
  case "xbox" :
  case "nintendo" :
  case "playstation" :
    echo $this->getLayout()->createBlock('cms/block')->setBlockId('console')->toHtml();
    break;
  default :
    //here you can put a default other block or show nothing or whatever you want to do if the product is not a console
}

现在,您可以通过添加更多case "other console" :语句来添加更多控制台

还有其他方法。您可以根据属性值创建所有控制台的数组,然后使用inArray();。-如果您的客户通过Magento管理员将更多控制台添加到属性中,则通常情况下会更好。

**编辑**,遵循以下评论

如果'platform'属性为multiselect,则$_product->getAttributeText('platform')如果选择了一项,则为字符串,但是如果选择了多项,则为数组。因此,您需要处理可以是字符串或数组的单个变量。在这里,我们将字符串转换为数组,并使用PHP的方便的array_intersect()函数

我建议:

$platformSelection = $_product->getAttributeText('platform');
if (is_string($platformSelection))
{
    //make it an array
    $platformSelection = array($platformSelection); //type casting of a sort
}

//$platformSelection is now an array so:

//somehow know what the names of the consoles are:
$consoles = array('xbox','nintendo','playstation');

if(array_intersect($consoles,$platformSelection)===array())
{
    //then there are no consoles selected
    //here you can put a default other block or show nothing or whatever you want to do if the product is not a console
}
else
{
    //there are consoles selected
    echo $this->getLayout()->createBlock('cms/block')->setBlockId('console')->toHtml();
}

请注意,array_intersect()函数严格比较数组元素,===因此区分大小写,array()如果没有交集,该函数将返回一个空数组

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章