Passing an array from block file to template file
-
16-10-2019 - |
Question
I have a collection of Dealer Stores. I have implemented a function that calculates the distance of all stores from the location of the customer and i have an array of respective distances. I have added the logic in Block.php file.
Now I want this array to be accessed from a template file. How do i implement this?
All answers i get from web are exact opposite of what is want - Passing data from template file to block file
Any help would be appreciated..
Solution
The template is renderer inside of the block class context, this means whatever information you put in $block->setMyPersonalVar($value)
can be read with $this->getMyPersonalValue()
inside the template. So as long as you have a reference to the block class in $block, you can set any value on it.
This can be used in the block class itself, e.g. in toHtml
or in the controller class $this->getLayout()->getBlock('nameInLayout')->setMyPersonalValue()
or wherever you want, e.g. in observers with Mage::app()->getLayout()->getBlock('nameInLayout')->setMyPersonalValue()
The alternative is to use Mage::register('name', $value)
and Mage::registry('name')
If this doesn't work my first guess is: The code is executed in the wrong order
OTHER TIPS
Okay let's consider an example:
your Block file consists of the function which returns your "Array", like
public function someFunction(){
//your logic
return $your_array;
}
in your config.xml
<config>
...
<frontend>
...
<layout>
<updates>
<yournamespace_yourmodule module="Yournamspace_YourModule">
<file>something.xml</file>
</yournamespace_yourmodule>
</updates>
</layout>
in app/design/frontend/default/your_theme/layout/something.xml
<?xml version="1.0" encoding="UTF-8"?>
<layout version="0.1.0">
<block_in_which_you_want_your_template>
<reference name="parent_block_name">
<block type="yourmodule/block_path" name="unique_name" template="path/to/your/template.phtml" /> <!-- important part of this answer -->
</reference>
...
now in your template.phtml
call $this->someFunction()
to get the array.
the key is declaring the block with your template file in something.xml, so that all the members from your block can be accessed in the template with the object ($this
).