Componentized Templates
组合的模板
This tip is a bit of a hack, but still a neat idea. Use at your own risk. ;-)
这项技巧有点普通,但是仍然是个不错的思想,如果要使用的话,自担风险。;-)
Traditionally, programming templates into your applications goes as follows: First, you accumulate your variables within your PHP application, (maybe with database queries.) Then, you instantiate your Smarty object, assign the variables and display the template. So lets say for example we have a stock ticker on our template. We would collect the stock data in our application, then assign these variables in the template and display it. Now wouldn't it be nice if you could add this stock ticker to any application by merely including the template, and not worry about fetching the data up front?
传统上,把模板编入你的应用程序中步骤如下:首先,你累计一下你的PHP程序中的变量,(可能用到数据库查询。)然后,你实例化一个你的Smarty对象,给变量赋值并且输出这个模板。因此,例如我们说我们在我们的模板里有一个资源标记。我们可以在我们的应用程序中收集这些资源数据,然后给模板中的这些变量赋值并输出。现在如果你仅仅是通过包含这些模板就可以把资源标记加入到任何一个应用程序中不是很好吗?
You can embed PHP into your templates with the {php}{/php} tags. With this, you can setup self contained templates with their own data structures for assigning their own variables. With the logic embedded like this, you can keep the template & logic together. This way no matter where the template source is coming from, it is always together as one component.
你可以通过使用{php}{/php}这两个标签来在你的模板里嵌入PHP。这样,你就能够建立包含自身的使用自己的数据结构的模板来给他们自身的变量赋值。通过像这样逻辑的嵌入,你能够把模板和逻辑性结合起来。这种方法使得模板不管源于何处总是像一个构件一样组合在一起。
As of Smarty 1.5.0, there is even a cleaner way. You can include php in your templates with the {include_php ...} tag. This way you can keep your PHP logic separated from the template logic. See the include_php function for more information.
就像Smarty 1.5.0,这里有一种更清晰的方法。你可以在你的模板里使用{include_php ...}这些标签来包含php。使用这种方法,你能够保持PHP的逻辑性和模板的逻辑性分离。参照include_php 这个函数来获得更多信息。
Example 18-8. componentized template with include_php 例 18-8. 使用include_php组合的模板
|