简体   繁体   中英

How to include php code in .tpl file

I have a small school project which I've almost finished. But now I have to change my working code and use template instead. I chose Smarty. Table displays data from a form. Data is stored in the text file and each element is on new line. Everything worked before but now that I can't figure out how to how to display my table. With my current code, my page turns white. I debugged it and got an error "is deprecated, use SmartyBC class to enable". I tried setting new smarty, I also tried using template function (plugin) but I still get white page. Any suggestions would be appreciated! My table.php code: ($items function reads from the file)

<?php
$count = 0;
if (isset($Items)){
    foreach ($Items as $item) {
        if($count == 0){
            print "<tr><td>$item</td>";
            $count += 1;
        } else if($count == 1) {
            print "<td>$item</td>";
            $count +=1;
        } else if($count == 2) {
            print"<td>$item</td></tr>";
            $count = 0;
        }

    }
}

tpl file

    <table>
    <tr>
        <th>Name</th>
        <th>Lastname</th>
        <th>Phone</th>
    </tr>
    {include_php file='table.php'}
</table>

Edit: I used $smarty = new SmartyBC(); and changed to {php} tags. It no longer shows white screen but the table.php code doesn't work -the table doesn't show.

Is there a smarter way to do this? Other than including php file? Edit: I got it working by using foreach loop inside the tpl but I wonder if it's the right way to do this?

Use {php} tag then include the php file path inside it

{php}
  include('table.php');
{/php}

You should not inject php code in any kind of template (not only Smarty). Load your data and perform your logic in php and render in the templating. engine. There is no need for template functions or to include php in your case.

PHP file

// Initiate smarty
$smarty = new Smarty ...;
...

// Somehow load your data from file
$itemsFromFile = somehow_load_data_from_file( ... );
...

// PAss your data to Smarty
$smarty->assign('items', $itemsFromFile);
...

// Render your template
$smarty->display( ... );

TPL file

<table>
    <tr>
        <th>Name</th>
        <th>Lastname</th>
        <th>Phone</th>
    </tr>

    {foreach $items as $key => $item}
        {if $key % 3 == 0}
            <tr>
        {/if}
                <td>$item</td>
        {if $key % 3 == 2}
            </tr>
        {/if}
    {/foreach}
</table>

Use the advantages of the templating engine. You can use modulus of three instead of counting to two and then reseting to zero.

Sources:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM