【发布时间】:2022-01-19 00:40:51
【问题描述】:
我在寻找有效替换模板文件中占位符的方法时遇到了这个old post。
一切似乎都正常,但是有一些值是可选的,我能做的最好的就是用空字符串替换占位符,这仍然会留下空行。
我正在测试的当前代码如下:
test.php:
<?php
$text = file_get_contents('test.html');
$pattern = '/{{{([a-zA-Z0-9_]+)}}}/';
$text = preg_replace_callback($pattern, 'produce_replacement', $text);
echo $text;
function produce_replacement($match) {
$producerName = 'evaluate_'.strtolower($match[1]);
return function_exists($producerName) ? $producerName() : null;
}
function evaluate_test1() {
ob_start();
include'test_include.php';
$test4 = ob_get_clean();
return $test4;
}
function evaluate_footer() {
if (isset($blah)) {
$val = 'some string';
} else {
$val = '';
}
return $val;
}
?>
test.html(模板文件):
<html>
<head></head>
<body>
<p>Test1: {{{test1}}}</p>
<p>Test2: {{{test2}}}</p>
<p>Test3: {{{test3}}}</p>
<p>Test4: {{{test4}}}</p>
{{{footer}}}
</body>
</html>
test_include.php:
<?php
$a = 'Hi, ';
$b = 'jeff!';
echo $a.$b;
?>
所以{{{footer}}} 将被替换为$val,这将是一些字符串 或将保留一个空行。我怎样才能摆脱那个空白行?
【问题讨论】:
-
这并不是模板文件应该如何工作的。考虑您实际上有
{{{footer}}}\n,其中\n是您的模板文件的一部分。通常,您不希望您的模板引擎只丢弃模板文件中的字符(引擎怎么会知道\n不是故意的?)所以它不删除换行符是预期的,并且可能是好的行为。为什么不直接将{{{footer}}}移到上一行的末尾? -
你应该使用真正的模板库,它可以让你编写条件表达式。
-
@TheGentleman - 将
{{{footer}}}移动到上一行的末尾会去掉空行但是如果{{{footer}}}不为空,我想我可以做到$val = "\n".'<div>some string</div>';
标签: php templates placeholder