gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 20:58:25 24 4
gpt4 key购买 nike

我有一个即将完成的小型学校项目。但是现在我必须更改我的工作代码并改用模板。我选择了聪明人。表显示来自表单的数据。数据存储在文本文件中,每个元素都在新行上。之前一切正常,但现在我不知道如何显示我的表格。使用我当前的代码,我的页面变白了。我调试它并得到一个错误“已弃用,使用 SmartyBC 类启用”。我尝试设置新的 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 代码不起作用 - 表格不显示。

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

最佳答案

你不应该在任何类型的模板中注入(inject) php 代码(不仅仅是 Smarty)。加载数据并在 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>

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

来源:

关于php - 如何在 .tpl 文件中包含 php 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50082717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com