Partials are HTML files, like views. But unlike views, partials are not connected to any action. You can create partial files with any names and display them on your pages when you need. There are 3 cases when you may want (or need) to use partials:
- Displaying common elements of pages. For example, if you have 10 pages with a same header, it is a good idea to move the header code to a partial.
- Simplifying a view code. If you are developing a complex page, you may simplify the code by moving parts of the markup into partials.
- Updating page elements using AJAX. The AJAX features will be explained later in this guide.
Creating and rendering a partial
Imagine that you need to display a common header on many pages of some controller. Instead of repeating the header markup on all pages (in all views), it is better to create a partial and put the header code into it. Partial files should be located in the same directory with controller views. Thus, all controller views and partials should be in the same directory.
Names of partial files should start from the underscore character (_). A suitable name for the header partial is _header.htm. After creating the partial and moving the header code to it, you can replace the header markup in your views with the following code:
<? $this->renderPartial('header') ?>
Please note that you don't need to specify the underscore symbol in the partial name when you call the renderPartial() method.
Passing PHP variables to partials
In the Adding a back-end user interface article we demonstrated how you can pass PHP variables from an action to a view, using the viewData field of the controller object. This method also works with partials - all variables created in the viewData field are available in partials which you render inside a view document.
You also can pass specific parameters into a partial from a view document using the second parameter of the renderPartial() method:
<? $this->renderPartial('header', array('customer_name'=>'John Doe')) ?>
If you use this code, the $customer_name PHP variable will be available in the _header.htm partial.
Want to Learn More?
This knowledge base is dedicated to helping you build successful eCommerce projects. To get the most value for your time, you'll want to download the free trial of LemonStand's eCommerce platform. If you're not ready, you can also browse our features and live demo.