問題描述
我在我的一個類方法中包含一個文件,并且在該文件中包含 html + php 代碼.我在該代碼中返回一個字符串.我明確地寫了 {{newsletter}}
然后在我的方法中我做了以下事情:
I'm including a file in one of my class methods, and in that file has html + php code. I return a string in that code. I explicitly wrote {{newsletter}}
and then in my method I did the following:
$contactStr = include 'templates/contact.php';
$contactStr = str_replace("{{newsletter}}",$newsletterStr,$contactStr);
但是,它不會替換字符串.我這樣做的唯一原因是當我嘗試將變量傳遞給包含的文件時,它似乎無法識別它.
However, it's not replacing the string. The only reason I'm doing this is because when I try to pass the variable to the included file it doesn't seem to recognize it.
$newsletterStr = 'some value';
$contactStr = include 'templates/contact.php';
那么,如何實現(xiàn)字符串替換方法?
So, how do I implement the string replacement method?
推薦答案
您可以使用 PHP 作為模板引擎.不需要 {{newsletter}}
結構.
You can use PHP as template engine. No need for {{newsletter}}
constructs.
假設您在模板文件中輸出一個變量 $newsletter
.
Say you output a variable $newsletter
in your template file.
// templates/contact.php
<?php echo $newsletter; ?>
要替換變量,請執(zhí)行以下操作:
To replace the variables do the following:
$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`
通過這種方式,您可以構建自己的模板引擎.
In this way you can build your own template engine.
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();
最好的一點是:您可以立即在模板中使用條件語句和循環(huán)(完整的 PHP).
The best thing about it: You can use conditional statements and loops (full PHP) in your template right away.
使用它以獲得更好的可讀性:https://www.php.net/manual/en/control-structures.alternative-syntax.php
Use this for better readability: https://www.php.net/manual/en/control-structures.alternative-syntax.php
這篇關于替換 php 文件中的 {{string}}的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!