如何使用Magento布局xml文件中的操作方法



示例

mylayoutfile.xml

<layout>
<default>
<reference name="header">
<block type="mynamespace_mymodule/view" name="mynamespace_mymodule" output="toHtml" template="mymodule/html/view.phtml">
<action method="setTest"><param1>myparam1</param1><param2>myparam2</param2></action>
</block>
</reference>
</default>
</layout>

app/code/local/Mynamespace/Mymodule/Block/View.php

class Mynamespace_Mymodule_Block_View extends Mage_Core_Block_Template{
public $test = "before any params";
public function setTest($passedparam1,$passedparam2){
$this->test = $passedparam1 ." ". $passedparam2;
}
}

app/design/…//mymodule/html/view.phtml

<?php
echo "<pre>";
print_r($this->test);  //myparam1 myparam2
echo"</pre>";
die();

解释

mylayoutfile是通过模块config.xml 在更新中编译的

mynamespace_module的块类前缀也在模块config.xml 中定义

mynamespace_module/view被设置为块类型并实例化,view.phtml的输出文件被设置为

执行一个操作,调用父节点块的方法setTest,传递两个值为myparam1和myparam2的参数。

在setTest函数内部,类参数"test"被设置为等于"myparam1-myparam2">

模板文件app/design/…//mymodule/html/view.phtml被加载,我们回显$this->test的值($this指的是早期实例化的块类Mynamespace_mymodule_block_view)

问题

  1. 哪些用例可以使用这种方法
  2. 你能传递字符串以外的任何东西吗?(对象,数组)
  3. automagic setter和getter方法是否在布局文件中工作
  4. 是否可以使用逻辑(if、then、foreach、else等)
  5. 有没有不应该使用这种方法的情况
  6. 在布局文件中,我是否还缺少与块实例化相关的其他内容
  7. 在布局文件中,我是否缺少与操作相关的其他内容
  1. 可以用于多用途模板。查看catalog.xmlsetTitle的使用情况
  2. 任何事情都可以通过。数组可以在布局XML:中定义

    <action method="setFoo">
    <arbitrary>
    <key1>val1</key1>
    <key2>val1</key2>
    </arbitrary>
    </action>
    

    此外,参数节点可以执行助手方法,该方法的返回值将作为值传入:

    <action method="setFoo">
    <arbitrary helper="foo/bar" />
    </action>
    

    这将实例化一个helper&运行一个方法:Mage::helper('foo')->bar()。因此,返回值可以是您想要的任何值。此外,参数可以传递给子节点中的帮助程序!

  3. 块扩展了Varien_Object,所以是的,尽管setter是唯一合理的使用方式
  4. 这没有直接的逻辑。最接近的是操作的ifconfig属性,该属性将使用提供的参数调用Mage::getStoreConfigFlag(),并在配置值为true时处理该操作
  5. "[c]不应该使用"-不。"没关系"-是的
  6. 这里有很多细微差别(太多了,这里无法详述),但你已经有很多了。艾伦·斯托姆(Alan Storm)在他的书《无边缘法师布局》(No Frills Magento Layout)中得到了所有细微之处;不过,没有什么比自己探索极限更好的了

最新更新