使用PHP作为模板引擎
我不会争论只选择 PHP 的模板引擎。我选择不使用模板引擎,例如 Smarty,因为我想学习如何使用 PHP 和 HTML 正确设计模板。有人可以提供有关如何设计模板页面的链接或示例吗?
I am not going to argue about the choice of a template engine against only PHP. I choose not to use a template engine, like Smarty, because I would like to learn how to properly design a template using PHP and HTML. Could someone provide links or examples on how to design a template page?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
只需使用专为此目的而设计的 if/for/foreach 控制语言结构的替代 PHP 语法:
我还建议为非常相似的 HTML 输出创建视图助手,并使用它们而不是重复的 HTML 代码。
Just use alternative PHP syntax for if/for/foreach control language constructs which are designed specifically for this purpose:
I also suggest creating view helpers for HTML outputs that are very similar and use them instead of having repeated HTML code.
这真的没有那么困难。
It's really not all that difficult.
在我的框架中,我有加载视图的函数,然后将其输出到布局中:
布局如下所示:
im my framework i have function that loads view, and then outs it in layout:
Layout looks like this:
使用理查德的例子,但更简单:
Using Richard's example, but more simple:
如果您应该选择 MVC 风格的方法,您可能需要考虑什么,如果您将模板包含在对象内(其类方法之一),则模板文件内的
$this
将指向你调用它的对象。如果您想确保模板的某种封装,即如果您不想依赖全局变量来传递动态数据(例如来自数据库的数据),这可能非常有用。
What you might want to consider, if you should opt for a MVC-style approach, if you include your templates inside an object (one of its class methods) then
$this
inside the template file will point to the object you called it from.This can be very useful if you want to ensure some kind of encapsulation for your templates, i.e. if you do not want to rely on global variables to pass around dynamic data (e.g. from a database).
我使用过各种模板引擎,也设计了自己的模板引擎,随着时间的推移变得越来越复杂。我认为最好通过使用本机 php 内容来使其尽可能简单,而不是创建复杂的函数。 (这篇文章有一些优点:无聊的架构是好的< /a>)。当几个月或几年后回到项目时,我发现可读性和维护性要好得多。
例如:
-- templates/unsubscribe.php --
I've used various template engines, and designed my own as well, getting more elaborate over time. I think its best to keep it as simple as possible by using native php stuff, instead of creating elaborate functions. (this article has some good points: Boring Architecture is Good). What I found was much better readability and maintenance when coming back to a project after months or years.
For example:
-- templates/unsubscribe.php --