如何在 .tpl 文件中包含 php 代码

How to include php code in .tpl file

我有一个小的学校项目,我已经快完成了。但是现在我必须更改我的工作代码并改用模板。我选择了聪明人。 Table 显示表单中的数据。数据存储在文本文件中,每个元素都在新行上。之前一切正常,但现在我不知道如何显示我的 table。使用我当前的代码,我的页面变白了。 我调试它并得到一个错误"is deprecated, use SmartyBC class to enable"。我尝试设置新的 smarty,我也尝试使用模板功能(插件),但我仍然得到白页。任何建议,将不胜感激! 我的 table.php 代码:($items 函数从文件中读取)

<?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 文件

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

编辑: 我使用了 $smarty = new SmartyBC();并更改为 {php} 标签。它不再显示白屏,但 table.php 代码不起作用 - table 不显示。

有没有更聪明的方法来做到这一点?除了包含 php 文件之外? 编辑:我通过在 tpl 中使用 foreach 循环使其工作,但我想知道这样做是否正确?

使用 {php} 标签然后在其中包含 php 文件路径

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

您不应该在任何类型的模板(不仅是 Smarty)中注入 php 代码。加载您的数据并在 php 中执行您的逻辑并在模板中呈现。引擎。在您的案例中不需要模板函数或包含 php。

PHP 文件

// 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 文件

<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>

利用模板引擎的优势。您可以使用三的模数而不是数到二然后重置为零。

来源: