在PHP中包含模板文件并替换变量

4

我有一个.tpl文件,其中包含我的网页的HTML代码和一个.php文件,我想在其中使用HTML代码并替换一些变量。 例如,假设这是我的file.tpl文件:

<html>
<head>
<title>{page_title}</title>
</head>
<body>
Welcome to {site_name}!
</body>
</html>

我想在我的PHP文件中定义{page_title}{site_name},并将它们显示出来。
我们可以通过将页面代码加载到变量中,然后替换{page_title}{site_name},最后输出它们的方式来实现这一点。
但我不确定这是否是最好的方法,因为如果.tpl文件很大,可能会遇到一些问题。
请帮我找到最好的方法。谢谢 :-)

1
我会说:要么使用普通的PHP文件进行模板设计,要么使用像Twig、Smarty或Mustache这样的现有模板解决方案。如果你想自己发明一个模板系统,那么你应该知道自己在做什么,并且有充分的理由去创建另一个模板系统。 - deceze
1
当我看到人们在/为php中实现模板解决方案时,我总是感到不安,因为php实际上是构建在html内部使用的。你期望从使用模板中获得什么样的好处?在许多情况下,您可以通过使用干净结构的php/html代码来实现相同的效果。 - user238801
@Layne 有时候限制 PHP 的可用性是必要的。例如,如果允许用户创建模板,你不希望他们运行任何 PHP 代码。 - Tamás Barta
5个回答

13

你可以这样做:

$replace = array('{page_title}', '{site_name}');
$with = array('Title', 'My Website');

$contents = file_get_contents('my_template.tpl');

echo str_replace($replace, $with, $contents);

更新:删除了include,使用file_get_contents()


7
这将产生与file_get_contents相同的结果,但是由于PHP使用'include'进行评估,因此存在漏洞。如果您不想使用模板系统,建议使用file_get_contents - Tamás Barta

1

这里有一个简单的例子,希望可以起到作用

你的HTML代码:

<?php

$html= '
<div class="col-md-3">
    <img src="{$img}" alt="">
    <h2>{$title}</h2>
    <p>{$address}</p>
    <h3>{$price}</h3>
    <a href="{$link}">Read More</a>
</div>
';

?>

您要替换的数组

<?php 

$content_replace = array(
    '{$img}'    => 'Image Link',
    '{$title}'  => 'Title',
    '{$address}'=> 'Your address',
    '{$price}'  => 'Price Goes here',
    '{$link}'   => 'Link',
    );

$content = strtr($html, $content_replace );

echo $content;


 ?>

1
由于我搜索到了这篇文章,我将提供我的解决方案:
$replacers = [
    'page_title'=> 'Title',
    'site_name' => 'My Website',
];
echo preg_replace("|{(\w*)}|e", '$replacers["$1"]', $your_template_string);

你需要将你的模板转换为字符串。例如:
file_get_contents(), 
ob_start(); 
include('my_template.tpl'); 
$ob = ob_get_clean();

或者任何类似于此类的内容。

希望这能有所帮助!?


0

正如您所提到的,您可以将文件读入字符串并替换标记,或者您可以包含该文件,但在这种情况下,不要使用标记,而是插入 PHP 片段以回显变量,例如:

<html>
<head>
<title><?php echo $page_title ?></title>
</head>
<body>
Welcome to <?php echo $site_name ?>!
</body>
</html>

在这种情况下,您不需要在整个模板上运行str_replace。它还允许您轻松地在模板中插入条件或循环。这是我处理事情的方式。

它比str_replace快得多,但很容易受到攻击,因为任何PHP代码都可以从模板文件中运行。 - Tamás Barta
1
在模板文件中使用 PHP 会给模板设计人员带来麻烦。 - Ahmad Ameri

0

我使用类似上述的方法,但我也在寻找更好的解决方案。

我使用这个:

$templatefile = 'test.tpl';
$page = file_get_contents($templatefile);

$page = str_replace('{Page_Title}', $pagetitle, $page);
$page = str_replace('{Site_Name}', $sitename, $page);

echo $page;

抱歉提出一个已经回答的线程,但我正在寻找更好的方法来做到这一点。

我目前也在使用jQuery来实现这个功能,这样我就可以拥有动态页面而不需要完全重新加载。例如:

<div id="site_name"></div>

<script type="text/javascript">
$.ajax({
  type: 'GET',
  url: 'data.php',
  data: {
    info: 'sitename'
  }
  success: function(data){
    $('#site_name').html(data); 
    //the data variable is parsed by whatever is echoed from the php file
  }
});
</script>

示例数据.php文件:

<?php
  echo "My site";
?>

希望这也能帮到其他人。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接