我需要创建一个简单的模板引擎;不能使用Twig或Smarty等,因为项目中的设计师需要能够轻松地将她的HTML代码复制/粘贴到模板中,无需任何配置。它必须是非常易用的。
因此,我创建了一个允许她这样做的东西,即在{{ 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
编辑
最终创建了一个仓库,供任何有兴趣的人使用。