我有这个控制器:

...
public function insertAction() {
    $something = 'testcase';
    $this->loadLayout();
    $this->_title($this->__("the title"));
    $this->renderLayout();
}
...

我想访问 $something 在我的.phtml文档中,我该怎么做? (或以另一种方式放置它:我该如何访问 $something 在我的.phtml文件中)

有帮助吗?

解决方案

有几种方法可以做到这一点。

直接分配给块:

$block->assign($var);

或者

$block->assign(array('myvar'=>'value','anothervar'=>true));

然后,您可以在PHTML文件中访问它:

$this->myvar

使用法师注册表:

Mage::register('custom_var', $var);

然后使用它:

$var = Mage::registry('custom_var');

其他提示

您的PHTML必须由一个块渲染。该块必须在布局中具有名称。
您可以在打电话后执行此操作 $this->loadLayout();

$block = Mage::app()->getLayout()->getBlock('block_name_here')
if ($block){//check if block actually exists
   $block->setSomething($something);
}

然后,您可以在 phtml 文件喜欢

$value = $this->getSomething();
//or 
$value = $this->getData('something');

如果你们错过了,还有另一种方法可以完成此操作

使用会议

Mage::getSingleton('core/session')->setSomeSessionVar($data);// In the Controller
$data = Mage::getSingleton('core/session')->getSomeSessionVar(); // In the View;

资源

如果您在块控制器中。

class module_namespace_Block_example extends Mage_Core_Block_Template 
{
      protected $_var;

     public function __construct(){

         $this->_var = "something"; 


     }
}

然后在您的.phtml文件中

   <?php 
        $variable = $this->_var;
        echo $variable; // prints "something"

   ?>

   <h1>You're inside your phtml file...... <?php echo $variable;  //prints "something" ?></h1>

这很容易将数据从控制器发送到PHTML文件。

步骤1: - 首先创建模型类并从Varien_Object延伸

class Namespace_Modulename_Model_Modelfilename extends Varien_Object
{

}

步骤2: - 现在打开ContollerFile并将代码放入函数中。

$name='gaurav';
$this->loadLayout();
Mage::getSingleton('Modulename/Modelfilename')->setData('name',$name);
$this->renderLayout();

步骤3: - 打开PHTML文件并放置代码。

echo $name=Mage::getSingleton('Modulename/Modelfilename')->getData('name');

输出: - 'gaurav';

许可以下: CC-BY-SA归因
scroll top