gpt4 book ai didi

php - 如何使php有效地循环一个模板文件

转载 作者:行者123 更新时间:2023-12-05 06:41:19 24 4
gpt4 key购买 nike

我在 stack overflow 上发现了一个关于在 php 中加载模板文件的问题,这很好,但我希望多次循环一行模板文件。我读过的文章在这里[ PHP Content Separation .该页面上的最佳答案来自 prodigitalson 及其函数 GetTemplate。

现在我想使用这样的东西,但是如果我把他的函数放在一个循环中那么它就不会很有效,因为它会多次加载同一个文件。

所以我尝试了这个。我会得到包含的html。然后将其存储在变量中,然后再将其放入循环中。但是它没有用。

这是我的代码。数据已经在名为 $result 的数组中。

$salesTemp=$this->tempLine('salesTEM.php');
while($row = array_shift($result)):
echo $salesTemp;
endwhile;

private function tempLine($file){
ob_start();
require $file;
return ob_get_clean();
}

问题是我的变量没有在模板中更新。这是我的模板

<li class="list-group-item"><?php echo $Customer;?><span class="label label-primary pull-right">SALES</span></li>

那么有没有一种方法可以重写它以便更新我的 $Customer 变量。

我这样做是为了尝试将 php 和 html 分开。

最佳答案

我看到的代码的主要问题是,当声明 $salesTemp 并通过 tempLine() 方法运行时,会返回一个字符串(由于到 ob_get_clean() )。模板中的变量已经被解析,当字符串在循环中回显时,模板中的变量不会更新,因为它们已经被解析并处理成字符串。为了解决这个问题,我会:

while ($row = array_shift($result)) {

echo $this->tempLine('salesTEM.php', $Customer);
}

/**
* @return string
*/
private function tempLine($file, $Customer) {

ob_start();
require $file;
return ob_get_clean();
}

这将是获得您想要的东西的最短路径。如果您不想在每次迭代中包含模板,请尝试:

$salesTEM = include 'salesTEM.php';

while ($row = array_shift($result)) {

echo sprintf($salesTEM, $Customer);
}

/**
* salesTEM.php
*/
<li class="list-group-item">
%s
<span class="label label-primary pull-right">SALES</span>
</li>

有许多可用的框架可以开箱即用地提供此功能,并且可以仔细阅读以获取有关模板技术的更多信息。从本质上讲,通过函数(文件名和数据)传递信息并期望字符串返回是一种很好的形式。这也将使单元测试变得容易。让它被动地获取信息往往会使代码容易出错,例如:

while ($row = array_shift($result)) {

echo include 'salesTEM.php';
}

/**
* salesTEM.php
*/
<li class="list-group-item">
<?php echo $Customer;?>
<span class="label label-primary pull-right">SALES</span>
</li>

您可能不小心包含了该文件并且没有声明 $Customer 变量,从而导致难以发现错误。定义进出的所有内容,这将使它在未来更易于管理。

关于php - 如何使php有效地循环一个模板文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40721704/

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