I have one java script definition in view(.phtml) file. This java script has dynamic parameters like controller name and action name. To avoid duplicate code i want to put this code in helper file.
Now is it possible that i can use pure html and javascript code in helper file? If yes then how can i call that helper in my view file?
Or Is there any other best way to do this?
Thank you...
A view helper would not be the solution in this instance. More likely you will want to use a partial (which is a view helper). A view helper is something normally used to return
a piece of data to the view. A partial()
or partialLoop()
is used to display common html in the view (pieces of html that can be reused in multiple views).
Here is an example of a simple view helper, notice it returns a result:
<?php
class Zend_View_Helper_FormatDate extends Zend_View_Helper_Abstract
{
public function FormatDate($date) {
if ($date != NULL) {
$formatedDate = new DateTime($date);
$format = $formatedDate->format('M d, Y');
return $format;
} else {
return '';
}
}
}
//This is called in the view like any other function
<?php echo $this->FormatDate($date) ?>
Now a partial will contain Html (I'm petty sure JS will work as well)
Here is a partial that uses view helpers
fieldset><legend>Dates and Qualifications</legend>
<table>
<tr>
<td>Birth Date: </td><td><?php echo $this->escape($this->FormatDate($this->bdate)) ?></td>
</tr>
<tr>
<td>Seniority Date: </td><td><?php echo $this->escape($this->FormatDate($this->sendate)) ?></td>
</tr>
</table>
<table>
<tr>
<td>I'm a Lead:</td><td><?php echo $this->escape(ucfirst($this->ToBool($this->lead))) ?></td>
</tr>
<tr>
<td>Lead Date:</td><td><?php echo $this->escape($this->FormatDate($this->ldate)) ?></td>
</tr>
<tr>
<td>I'm an Inspector:</td><td><?php echo $this->escape(ucfirst($this->toBool($this->inspector))) ?></td>
</tr>
<tr>
<td>Admin Login:</td><td><?php echo $this->escape(ucfirst($this->toBool($this->admin))) ?></td>
</tr>
</table>
</fieldset>
call this partial in your view script, the first argument is the path of the partial the second argument is the data used in the partial
<?php echo $this->partial('_dates.phtml', $this->memberData) ?>
the data is sent from the controller action as usual $this->view->memberData = $memberData
This is common usage but not the only way to get data to the partial.
in this example the partial is at the default location /application/views/scripts
Hope this helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.