创建“模板解释器”的最佳方法是在 PHP 中
我正在托管一个用 PHP 编写的多区域解决方案,每个客户在一些 HTML 文件中都有自己的模板。现在我希望这些用户能够使用一些动态内容块,但他们无法使用 PHP。我想的是这样的:
在 HTML 文件中,如果我输入:
<ul>[menu-list]</ul>
将输出类似的内容:
<ul><li><a[...]>Home</a></li><li><a[...]>About</a></li>[...]</ul>
有没有比通过 file_get_contents() 和 preg_match_all 不断解析和缓存文件更好的方法? ()?
我想创建大约 20 个条目,例如 [menu-list]
,并且解析所有这些条目的每个文件对我来说似乎相当昂贵。
我将不胜感激任何建议。 =D
I'm hosting a multi area solution written in PHP, and each customer has its own template in some HTML files. Now I want these users to be able to use some chunks of dynamic content, but they can't be able to use PHP. I thought something like:
In the HTML file, if I put this:
<ul>[menu-list]</ul>
Will output something like:
<ul><li><a[...]>Home</a></li><li><a[...]>About</a></li>[...]</ul>
Is there any better way of doing it than keep parsing and caching files via file_get_contents()
and preg_match_all()
?
I want to create about 20 entries like [menu-list]
, and parsing every file for all of them seems quite expensive to me.
I'd appreciate any suggestion. =D
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许您应该考虑使用模板编译器而不是模板解释器。也就是说,您可以在模板修改后简单地执行替换,而不是每次加载页面时都执行整个替换过程。在模板编辑过程中,成本应该可以忽略不计。要实现此编译,您可以选择在某些面包屑中“编译”,以便可以向后返回,或者您可以简单地保存原始模板文件以供以后编辑。
或者,您可以考虑使用 PHP 变量命名约定并通过
eval
运行模板,但这会带来许多其他问题(例如安全威胁),因此不强烈推荐。Perhaps you should consider using a template compiler instead of a template interpreter. That is, instead of each time the page is loaded doing this whole replacement procedure you could simply perform the replacement after the template has been modified. During template editing the cost should be negligible. To implement this compilation you could choose to "compile" in some breadcrumbs so you can go backwards, or you can simply save the original template files for later editing.
Alternatively, you could consider using PHP variable naming conventions and running your templates through an
eval
, but this poses a number of other issues (like security threats) and doesn't come highly recommended.为什么你不能使用 Smarty 和朋友?我不想自己写你建议的内容。
Why can't you use Smarty and friends? I would not want to write what you suggest myself.