我在我的一个类方法中包含了一个文件,该文件中有html+php代码。我在那个代码中返回一个字符串。我明确地写了{{newsletter}}
,然后在我的方法中我做了以下操作:
$contactStr = include 'templates/contact.php';
$contactStr = str_replace("{{newsletter}}",$newsletterStr,$contactStr);
但是,它并没有替换字符串。我这样做的唯一原因是,当我试图将变量传递到包含的文件时,它似乎无法识别它
$newsletterStr = 'some value';
$contactStr = include 'templates/contact.php';
那么,我该如何实现字符串替换方法呢?
您可以使用PHP作为模板引擎。不需要{{newsletter}}
构造。
假设您在模板文件中输出了一个变量$newsletter
。
// templates/contact.php
<?= htmlspecialchars($newsletter, ENT_QUOTES); ?>
要替换变量,请执行以下操作:
$newsletter = 'Your content to replace';
ob_start();
include('templates/contact.php');
$contactStr = ob_get_clean();
echo $contactStr;
// $newsletter should be replaces by `Your content to replace`
通过这种方式,您可以构建自己的模板引擎。
class Template
{
protected $_file;
protected $_data = array();
public function __construct($file = null)
{
$this->_file = $file;
}
public function set($key, $value)
{
$this->_data[$key] = $value;
return $this;
}
public function render()
{
extract($this->_data);
ob_start();
include($this->_file);
return ob_get_clean();
}
}
// use it
$template = new Template('templates/contact.php');
$template->set('newsletter', 'Your content to replace');
echo $template->render();
最好的一点是:您可以立即在模板中使用条件语句和循环(完整的PHP)。
使用此选项可获得更好的可读性:https://www.php.net/manual/en/control-structures.alternative-syntax.php
这是我用于模板的代码,应该可以完成
if (preg_match_all("/{{(.*?)}}/", $template, $m)) {
foreach ($m[1] as $i => $varname) {
$template = str_replace($m[0][$i], sprintf('%s', $varname), $template);
}
}
可能有点晚了,但我看起来像这样。
问题是include不会返回文件内容,更简单的解决方案可能是使用file_get_contents函数。
$template = file_get_contents('test.html', FILE_USE_INCLUDE_PATH);
$page = str_replace("{{nombre}}","Alvaro",$template);
echo $page;
基于@da炒作
<?php
$template = "hello {{name}} world! {{abc}}'n";
$data = ['name' => 'php', 'abc' => 'asodhausdhasudh'];
if (preg_match_all("/{{(.*?)}}/", $template, $m)) {
foreach ($m[1] as $i => $varname) {
$template = str_replace($m[0][$i], sprintf('%s', $data[$varname]), $template);
}
}
echo $template;
?>
将output_buffers与PHP变量一起使用。它更加安全、兼容和可重复使用。
function template($file, $vars=array()) {
if(file_exists($file)){
// Make variables from the array easily accessible in the view
extract($vars);
// Start collecting output in a buffer
ob_start();
require($file);
// Get the contents of the buffer
$applied_template = ob_get_contents();
// Flush the buffer
ob_end_clean();
return $applied_template;
}
}
$final_newsletter = template('letter.php', array('newsletter'=>'The letter...'));
<?php
//First, define in the template/body the same field names coming from your data source:
$body = "{{greeting}}, {{name}}! Are You {{age}} years old?";
//So fetch the data at the source (here we will create some data to simulate a data source)
$data_source['name'] = 'Philip';
$data_source['age'] = 35;
$data_source['greeting'] = 'hello';
//Replace with field name
foreach ($data_source as $field => $value) {
//$body = str_replace("{{" . $field . "}}", $value, $body);
$body = str_replace("{{{$field}}}", $value, $body);
}
echo $body; //hello, Philip! Are You 35 years old?
注意-替换的另一种方法是使用注释语法。
但是,为什么使用三个方括号有效呢?
默认情况下,方括号允许您在字符串中插入变量。
如:
$name = 'James';
echo "His name is {$name}";
因此,当你在变量周围使用三个方括号时,最里面的方括号专用于变量的插值,以显示它们的值:
这个{{{$field}}}
变成这个{{field}}
最后用str_replace
函数替换两个方括号。
不,不包括在内。include
正在执行php代码。它的返回值是包含的文件返回的值,或者如果没有返回:1。
你想要的是file_get_contents()
:
// Here it is safe to use eval(), but it IS NOT a good practice.
$contactStr = file_get_contents('templates/contact.php');
eval(str_replace("{{newsletter}}", $newsletterStr, $contactStr));