在这篇教程中我将演示如何注入你需要的自定义变量到一个cms静态块,使用{{var variable_name}}标签。如果你正在处理email模版,那么你会看到这个。(本质是我们使用和email模版同样的用来注入变量的筛选器。

首先,让我们假设几件事情:

    包命名为'Company',模块命名为'Module'
  1. 你知道如何创建一个php模型和新的块类。例子中的块别名是‘module/dynamic’
  2. 动态块的模版是dynamic.phtml
  3. 静态cms块的id是‘static_block’(你需要在后台创建它)
  4. 你需要添加当前用户的email到静态块。什么时候显示模块和文本范围的逻辑。

第一步,我们看下模版文件,里面只使用我们想要创建块类的方法:

<?php if(Mage::getSingleton('customer/session')->getCustomer()->getId()) : ?>
	<?php echo $this->getStaticBlock();?>
<?php endif;?>

如你所见,我们只检查客户是否存在。下面我们看动态块类里的逻辑:

<?php
/**
 * Just another block class
 */
class Company_Module_Block_Dynamic extends Mage_Core_Block_Template
{
	/**
	 * This getter will return the html of your static block
	 * @return string
	 */
	public function getStaticBlock()
	{
		// loading the static block
		$block = Mage::getModel('cms/block')
		->setStoreId(Mage::app()->getStore()->getId())
		->load('static_block');
		/* @var $block Mage_Cms_Model_Block */
 
		// setting the assoc. array we send to the filter.
		$array = array();
		// the array keys are named after the tags in the static block. let's say $array['customer_email'] is {{var customer_email}} in the static block. you can set as many variables you need.
		$array['customer_email'] = Mage::getSingleton('customer/session')->getCustomer()->getEmail();
 
		// loading the filter which will get the array we created and parse the block content
		$filter = Mage::getModel('cms/template_filter');
		/* @var $filter Mage_Cms_Model_Template_Filter */
		$filter->setVariables($array);
 
		// return the filtered block content.
		return $filter->filter($block->getContent());
 
	}
}
?>

现在,在你CMS中的static_block块中添加 {{var customer_email}}标签,它将被动态地添加到CMS块。

360magento提供专业的基于magento系统的电商网站开发服务,如有需求或相关咨询,请与我们联系