Php 基于头部定义的各种条件,在页面中间回响动态内容
我试图动态地回显一些预定义的模板('template-file-for-output.php'),其中填充了一些数据(来自$var数组),这些数据位于许多页面的特定位置(例如,页面'page.php') 基本上我的目标是建立一个系统Php 基于头部定义的各种条件,在页面中间回响动态内容,php,templates,output-buffering,Php,Templates,Output Buffering,我试图动态地回显一些预定义的模板('template-file-for-output.php'),其中填充了一些数据(来自$var数组),这些数据位于许多页面的特定位置(例如,页面'page.php') 基本上我的目标是建立一个系统 我设置了逻辑(在'logic.php'文件中)、所需的函数(在'functions.php'中)、模板(在'template file for output.php'中) 通过它,我的同事可以创建他们想要的任何页面(为了示例,就像在“page.php”中一样),内
- 我设置了逻辑(在'logic.php'文件中)、所需的函数(在'functions.php'中)、模板(在'template file for output.php'中)
- 通过它,我的同事可以创建他们想要的任何页面(为了示例,就像在“page.php”中一样),内容和HTML都可以随心所欲,只需要在文件的开头包含functions.php和logic.php文件,和echo语句,以使动态内容显示在他们希望显示的位置
- logic.php:
- functions.php:
- template-file-for-output.php:
一些内容带有标记等,由$var数组的一些值填充
从$var中提取$Example变量的示例
另一个变量也来自$var
- page.php:
网站的一页
有趣的事情(希望如此)
将ob_get_contents更改为ob_get_clean,ob_get_contents获取缓冲区的内容,但保留其完整性。之前的代码为缓冲区分配了一个变量,然后将缓冲区刷新为输出
function outputContent($var, $errors = null)
{
extract($var);
ob_start();
include 'template-file-for-output.php';
$output = ob_get_clean();
return $output;
}
撇开目前已有的模板系统已经非常有效地解决了这个问题这一点不谈 我会尝试不包含模板文件,而是读取包含file_get_内容的文件,然后在输出缓冲区部分中进行回显
function outputContent($var, $errors = null)
{
extract($var);
ob_start();
echo file_get_contents('template-file-for-output.php');
$output = ob_get_clean();
return $output;
}
谢谢你的建议,你能解释一下为什么它比Orangepill的解决方案“更好”吗?函数outputContent将在页面的头部调用,但其输出必须仅在用户将代码放在页面中的地方出现,您的解决方案是否也能做到这一点(我看到了“echo file\u get\u content”,我很好奇)?
<p>Some content with tags and so on, filled in by some values of the $var array.</p>
<p>Example with the $example variable extracted from $var <?php echo $example; ?></p>
<p>Another variable also from $var <?php echo $anotherVariable; ?>
<?php
include 'logic.php';
include 'functions.php';
?>
<!DOCTYPE html>
<html>
<head><title>A page of the site</title></head>
<body>
<p>Something interesting (hopefully).</p>
<?php echo $output; ?>
</body>
</html>
function outputContent($var, $errors = null)
{
extract($var);
ob_start();
include 'template-file-for-output.php';
$output = ob_get_clean();
return $output;
}
function outputContent($var, $errors = null)
{
extract($var);
ob_start();
echo file_get_contents('template-file-for-output.php');
$output = ob_get_clean();
return $output;
}