[英]What is the best way to Include meta tags in the head section of a PHP template?
[英]What is the best way to include a php file as a template?
我有簡單的模板,主要是html,然后通過PHP從SQL中提取一些東西,我想將這個模板包含在另一個php文件的三個不同位置。 做這個的最好方式是什么? 我可以包含它然后打印內容嗎?
模板示例:
Price: <?php echo $price ?>
並且,例如,我有另一個php文件,只有在SQL中的日期后兩天以上才會顯示模板文件。
最好的方法是在關聯數組中傳遞所有內容。
class Template {
public function render($_page, $_data) {
extract($_data);
include($_page);
}
}
要構建模板:
$data = array('title' => 'My Page', 'text' => 'My Paragraph');
$Template = new Template();
$Template->render('/path/to/file.php', $data);
您的模板頁面可能是這樣的:
<h1><?php echo $title; ?></h1>
<p><?php echo $text; ?></p>
Extract是一個非常漂亮的函數,它可以將一個關聯數組解包到本地命名空間中,這樣你就可以像echo $title;
這樣做echo $title;
。
編輯:添加下划線以防止名稱沖突,以防您提取包含變量'$ page'或'$ data'的內容。
將您的數據放在數組/對象中,並將其作為第二個參數傳遞給以下函數:
function template_contents($file, $model) {
if (!is_file($file)) {
throw new Exception("Template not found");
}
ob_start();
include $file;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
然后:
Price: <?php echo template_contents("/path/to/file.php", $model); ?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.