如何从 Magento 中的 phtml 中获取 xml 中的块标签?

How to fetch block's label in xml from phtml in Magento?

我的布局文件中有一个自定义块,如下所示:

<block type="xxx/xxx" name="xxx" template = "bar.phtml">
<label>Foo</label>
</block>

如何从 bar.phtml 中获取标签的值?

请注意,我不想使用 setData 函数来设置我的变量并传递它。 我想从 phtml(或其他任何地方)中提取标签内的值。我希望它清楚。

在您的 XML 中,使用操作方法 setData

<block type="xxx/xxx" name="xxx" template = "bar.phtml">
    <action method="setData">
        <label>Foo</label>
    </action>
</block>

然后在您的 bar.phtml 文件中,您可以使用 $this->getData('label'):

检索它
<?php echo $this->getData('label') ?>

我认为没有真正经典的 Magento 方法可以做到这一点,因为就我们所说的前端而言,不会显示块用途的标签。

label: This element is introduced since Magento 1.4. It defines the label of the handle which is shown as a descriptive reference in some areas of the admin panel.

Source

我真诚地建议您远离下面的代码。但如果那真的是你想要实现的,这是一种方式:

首先我们得到 layout = 一个大 xml 页面布局的串联,其中包含定义块的 xml,因此我们的标签

$layout = $this->getLayout();

然后我们在布局中获取当前块名称

$currentBlockNameInLayout = $this->getNameInLayout();

我们可以,然后在模板中获取代表当前区块的XML节点。
getXpath() 做 returns 一个数组,所以这就是为什么我使用 list() 从这个数组中取出第一项

list($currentBlockInLayout) = $layout->getXpath("//block[@name='".$currentBlockNameInLayout."']");

我们得到了我们想要的并且可以回显它的标签元素

echo $currentBlockInLayout->label;

不过请注意,这是一个类型为 Mage_Core_Model_Layout_Element 的对象,因此如果您想执行除显示之外的任何其他操作,则必须使用 __toString() 方法

var_dump( $currentBlockInLayout->label->__toString() );

完整代码:

$layout = $this->getLayout();
$currentBlockNameInLayout = $this->getNameInLayout();
list($currentBlockInLayout) = $layout->getXpath("//block[@name='".$currentBlockNameInLayout."']");
echo $currentBlockInLayout->label;
var_dump( $currentBlockInLayout->label->__toString() );