When you use Smarty templates, you could be hard coding or retrieving arrays from a database query. In most situations, your logic ‘.php’ file will create the arrays and the ‘.tpl’ file will be used for presenting the arrays within HTML. The easiest way to show how this can be done is to show you a sample ‘.php. file and a ‘.tpl’ file.
The example uses 4 arrays; $leads, $myarray, $myarray1, $myarray2 and $myarray3. After all arrays have been created, they are assigned Smarty template variables. This must be done or the ‘.tpl’ file cannot use them. Once they are assigned, the display() method calls the ‘.tpl’.
Since the variables can now be used with the ‘.tpl’ file, several foreach loops are created for each array. As you code and test the examples, you will gain some methods for which you can display arrays in foreach loops.
Logic(.php file)
require_once(SMARTY_DIR . 'Smarty.class.php'); $smarty = new Smarty(); $leads = array("John","Paul","George"); $myarray = array("key" => "Blue Jays", "key2"=> "Giants", "key3" => "Rangers"); $myarray2 = array("Blue Jays", "Giants", "Rangers"); $myarray3 = Array(Array ( "id" => "1", "lastname" => "Smith", "firstname" => "John", "email" => "js@example.com", "phone" => "5555666" , "subject" => "A", "notes" => "Lots", "date" => "2012-01-01" ), Array( "id" => "2", "lastname" => "Jones", "firstname" => "Paul", "email" => "paul@example.com", "phone" => "5555555" , "subject" => "B", "notes" => "None", "date" => "2012-01-02" )); $smarty->assign("leads",$leads); $smarty->assign("myarray",$myarray); $smarty->assign("myarray2",$myarray2); $smarty->assign("myarray3",$myarray3); $smarty->display("smarty.tpl"); //compile and display output
Presentation (.tpl file)
{foreach item=lead from=$leads} <div style="width:40%;"> <strong>Profile of {$lead}</strong> </div> {/foreach} <br/> {foreach from=$myarray key="key" item="value"} <div style="width:40%;"> <strong>Item is {$key}{$value}</strong> </div> {/foreach} <br/> {foreach from=$myarray2 key="key" item="value"} <div style="width:40%;"> <strong>Item is {$key}{$value}</strong> </div> {/foreach}
Browser Output
Item is keyBlue Jays
Item is key2Giants
Item is key3Rangers
Item is 0Blue Jays
Item is 1Giants
Item is 2Rangers
Profile of John Smith
First Name: John
Last Name: Smith
Phone: 5555666
Email: js@example.com
Profile of Paul Jones
First Name: Paul
Last Name: Jones
Phone: 5555555
Email: paul@example.com
© 2018 ALL Rights Reserved | Sitemap
Vancouver | North Vancouver | Burnaby | Richmond | Coquitlam | Port Coquitlam | Surrey | Langley | Maple Ridge | Mission | Abbotsford | Kamloops | Kelowna | Victoria | Squamish | Whistler | Pemberton