View Helper, Partial View or Something Else

2019-05-18 10:59发布

问题:

I am new to Zend Framework and I have a question about something I am trying to do.

The main content of most pages of the application that I am working on will consist of 1 or more div elements that need to be styled the same.

Here is an example of the HTML that I want to generate:

<div id='admin-locations' class='panel'>
    <header class="panel-header">
        <h2>Locations</h2>
    </header>
    <div class='panel-content'>
        <div id='locations-table' class='google-vis-table'></div>
        <form id='locations'>
            ...
        </form>
    </div>
</div>

I know I can easily do this by pushing the form to my view script in my controller then adding this code to my controller.

<div id='admin-locations' class='panel'>
    <header class="panel-header">
        <h2>Locations</h2>
    </header>
    <div class='panel-content'>
        <div id='locations-table' class="google_vis_table"></div>
        <?php 
            echo $this->formLocations;
        ?>
    </div>
</div>

But that is not DRY.

The example I used here has a Google Visualization Table and a Zend Form in it's content. Sometimes the panels will need to contain a form. Sometimes they won't, so I don't think form decorators are the way to go. So basically, the id of the panel, the panel header text and the content of div class='panel-content' need to be dynamic. Everything else will stay the same from panel to panel.

What is my best option here?

回答1:

You might want to consider using partials: http://framework.zend.com/manual/en/zend.view.helpers.html#zend.view.helpers.initial.partial

For example, you could have an admin-locations.phtml partial that contains:

<div id='admin-locations' class='panel'>
    <header class="panel-header">
        <h2>Locations</h2>
    </header>
    <div class='panel-content'>
        <div id='locations-table' class="google_vis_table"></div>
        <?php echo $this->form; ?>
    </div>
</div>

Now you can simply repeatedly call the partial within a view, with or without supplying a form:

...
echo $this->partial('admin-locations.phtml');
echo $this->partial('admin-locations.phtml', array('form' => $this->yourForm);
echo $this->partial('admin-locations.phtml');
...

Hope this helps.