我需要创建一个简单的模板引擎;我不能使用Twig或Smarty等,因为该项目的设计人员需要能够将HTML复制/粘贴到模板中,而无需进行任何配置,混乱或混乱。它必须really简单。
因此,我通过将她的内容放在{{ CONTENT }}
{{ !CONTENT }}
标签之间,创建了一个允许她做到这一点的东西。
我唯一的问题是,我想确保如果她在标签中使用多个空格-或没有空格-它不会中断;即{{ CONTENT }}
或{{CONTENT}}
我下面的功能可以完成此任务,但恐怕这可能会导致过大杀伤力。有人知道简化此功能的方法吗?
function defineContent($tag, $string) {
$offset = strlen($tag) + 6;
// add a space to our tags if none exist
$string = str_replace('{{'.$tag, '{{ '.$tag, $string);
$string = str_replace($tag.'}}', $tag.' }}', $string);
// strip consecutive spaces
$string = preg_replace('/\s+/', ' ', $string);
// now that extra spaces have been stripped, we're left with this
// {{ CONTENT }} My content goes here {{ !CONTENT }}
// remove the template tags
$return = substr($string, strpos($string, '{{ '.$tag.' }}') + $offset);
$return = substr($return, 0, strpos($return, '{{ !'.$tag.' }}'));
return $return;
}
// here's the string
$string = '{{ CONTENT }} My content goes here {{ !CONTENT }}';
// run it through the function
$content = defineContent('CONTENT', $string);
echo $content;
// gives us this...
My content goes here
最终为感兴趣的人创建了一个仓库。
我建议看一下将变量提取到模板范围内的方法。与替换方法相比,它更容易维护且开销更少,并且对于设计人员而言通常更易于使用。在其基本形式中,它只是PHP变量和短标签。
取决于您生成的那一侧,例如一个表及其行(或完整的内容块)-可能只是<?=$table?>
;)设计人员的工作量少,您的工作量大。或仅提供一些渲染示例和帮助程序,因为即使使用未经培训的设计师,复制/粘贴示例也应始终有效。
模板
模板只是混合了<?=$variable?>
的HTML-整洁。
src/Templates/Article.php
<html>
<body>
<h1><?=$title?></h1>
<div><?=$content?></div>
</body>
</html>
用法
src/Controller/Article.php
...
// initalize
$view = new View;
// assign
$view->data['title'] = 'The title';
$view->data['content'] = 'The body';
// render
$view->render(dirname(__DIR__) . '/Templates/Article.php');
View / TemplateRenderer
这里的核心功能是render()
。包含模板文件,变量提取在闭包中进行,以避免任何变量冲突/范围问题。
src/View.php
class View
{
/**
* Set data from controller: $view->data['variable'] = 'value';
* @var array
*/
public $data = [];
/**
* @var sting Path to template file.
*/
function render($template)
{
if (!is_file($template)) {
throw new \RuntimeException('Template not found: ' . $template);
}
// define a closure with a scope for the variable extraction
$result = function($file, array $data = array()) {
ob_start();
extract($data, EXTR_SKIP);
try {
include $file;
} catch (\Exception $e) {
ob_end_clean();
throw $e;
}
return ob_get_clean();
};
// call the closure
echo $result($template, $this->data);
}
}
特别回答您的要求:
我唯一的问题是,我想确保她在标签中使用多个空格-或不使用空格-不会破损
我下面的功能可以完成此任务,但恐怕这可能会导致过大杀伤力。有人知道简化此功能的方法吗?
...功能的唯一“慢”部分是preg_replace
。请改用trim,以使速度略有提高。否则,不用担心。没有神奇的PHP命令可以执行您要执行的操作。
特别回答您的要求:
我唯一的问题是,我想确保她在标签中使用多个空格-或不使用空格-不会破损
我下面的功能可以完成此任务,但恐怕这可能会导致过大杀伤力。有人知道简化此功能的方法吗?
...功能的唯一“慢”部分是preg_replace
。请改用trim,以使速度略有提高。否则,不用担心。没有神奇的PHP命令可以执行您要执行的操作。