创建一个简单但灵活的模板引擎 [英] Creating a simple but flexible templating engine
问题描述
我正在尝试构建一个基本的模板引擎.就像已经开源的模板引擎一样,我正在使用搜索和替换技术.
I am trying to build a basic templating engine. Like the template engines already available as open source, I am using search and replace techniques.
然而,由于搜索和替换必须是硬编码的,所以它不是那么灵活.我的意思是说,作为一个例子,我正在使用这样的东西
However, as the search and replace have to be hardcoded, it is not so much flexible. What I mean to say is, as an example, I am using something like this
$templateMarkup = '<div class="title">{_TITLE_}</div>';
$renderedMarkup = str_replace("{_TITLE_}",$title,$templateMarkup);
echo $renderedMarkup;
如您所见,它是硬编码的.所以我必须有意识地了解所有占位符才能成功渲染.
As you can see, it is hardcoded. So I have to purposely know all the placeholders to accomplish a successful render.
我在正则表达式方面有点弱.但我知道,如果我可以开发一个正则表达式,它可以匹配所有以 {_
开头并以 _}
结尾的文本,并获得它们之间的值,我可能会能够创建灵活的模板引擎.
I am a little bit weak in regular expression. But I know, if I can develop a regex, which can match all the text starting with {_
and ending _}
and get the value in between them, I just might be able to create a flexible templating engine.
我需要正则表达式方面的帮助.
I need help with the regular expression.
如果我完全走错了路,请警告我.
If I am completely going the wrong way to accomplish, please do warn me.
<子>对于那些认为我在重新发明轮子的人.这是我的解释
For those who think I am reinventing the wheel. Here is my explanation
Templating engines, that are already available are quite unnecessarily complex.
My requirements are simple and so I am builidng my own simple engine.
推荐答案
您正在寻找的正则表达式是 {_(\w+)_}
,如果您的模板标签只是一个一个字.你会像这样使用它:
The regular expression you're looking for is {_(\w+)_}
, if your template tags are only ever a single word. You'd use it a bit like this:
<?php
$replacements = array(
"firstname" => "John",
"lastname" => "Smith"
);
$template_markup = "Hello {_firstname_} {_lastname_}";
if(preg_match_all('/{_(\w+)_}/', $template_markup, $matches)) {
foreach($matches[1] as $m) {
$template_markup = str_replace("{_".$m."_}", $replacements[$m], $template_markup);
}
}
echo $template_markup;
?>
您会看到 preg_match_all
在正则表达式周围有正斜杠,这些是分隔符.
You'll see the preg_match_all
has forward slashes surrounding the regular expression, these are delimiters.
更新:如果您想将正则表达式扩展到单个单词之外,那么在使用 .
匹配任何字符时要小心.最好使用类似这样的东西来指定要包含其他字符:{_([\w-_]+)_}
.[\w-_]
表示它将匹配字母数字字符、连字符或下划线.
Update: If you want to expand the regular expression beyond single words, then be careful when using .
to match any character. It's better to use something like this to specify that you want to include other characters: {_([\w-_]+)_}
. The [\w-_]
means it will match either alphanumeric characters, hyphens or underscores.
(也许有人可以解释为什么使用 .
可能是个坏主意?我不是 100% 确定).
(Perhaps someone can explain why using .
might be a bad idea? I'm not 100% sure).
这篇关于创建一个简单但灵活的模板引擎的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!