使用 str_replace 进行简单模板化
我只是首先进行尝试。
我只是想出了一个用简单的方式制作自己的想法:
class Template
{
function parse($template_file, $braces)
{
if(file_exists($template_file))
{
$template = file_get_contents($template_file);
foreach($braces as $brace => $replacement)
{
$brace = trim(strtoupper($brace));
$build = str_replace('{' . $brace . '}', $replacement, $template);
}
echo $build;
}
else
{
trigger_error('Template file does not exist: ' . $template_file, E_ERROR);
}
}
}
这是为了工作:
$template = new Template();
$template->parse('index_body.html', array('ONE' => 'one',
'TWO' => 'two',
'THREE' => 'three'));
index_body.html:
{ONE}
{TWO}
{THREE}
问题是,它只输出:
{ONE} {TWO} three
它总是替换最后一个大括号,怎么不是整个数组呢?
I'm just experimenting first of all.
I just came up with an idea of making my own in a simple way here:
class Template
{
function parse($template_file, $braces)
{
if(file_exists($template_file))
{
$template = file_get_contents($template_file);
foreach($braces as $brace => $replacement)
{
$brace = trim(strtoupper($brace));
$build = str_replace('{' . $brace . '}', $replacement, $template);
}
echo $build;
}
else
{
trigger_error('Template file does not exist: ' . $template_file, E_ERROR);
}
}
}
This in order to work:
$template = new Template();
$template->parse('index_body.html', array('ONE' => 'one',
'TWO' => 'two',
'THREE' => 'three'));
index_body.html:
{ONE}
{TWO}
{THREE}
The problem is, that it only outputs:
{ONE} {TWO} three
It always replaces the last brace, how come not the whole array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您始终会替换原始模板,而不是更新后的模板。要么继续分配
$template
,要么更新$build
You're always replacing against the original template, never against the updated one. Either keep assigning
$template
, or update$build
它仅替换最后一个位置,因为在每种情况下,您都将替换原始
$template
变量中的值。它不会在每次迭代时更新变量。It only replaces the last place because in each case, you're replacing the value in the original
$template
variable. It's not updating the variable each iteration.您回显 $build,每次 foreach 迭代都会重新分配它。
你应该写这个
You echo $build, which is being reassigned every foreach iteration.
You should've written this instead
怎么样使用完整的 php 引擎功能(类似于 smarty 界面):
只是为了实验:
How about using like full php engine power (similar to smarty interface):
just for experimenting:
您的 $build 在每次迭代中都会被覆盖。这将解决这个问题。
Your $build is overwritten in each iteration. This will solve the issue.