electblake / mustache
CakePHP 视图助手插件,用于 Mustache 模板语言
Requires
- composer/installers: *
- mustache/mustache: dev-master
This package is not auto-updated.
Last update: 2024-09-14 15:00:47 UTC
README
Mustache 视图助手(最初为 CakePan)用于渲染 Mustache 模板。它还可以加载和解析局部模板!
为什么在 CakePHP 中使用 Mustache 模板?
便携性和可扩展性!如果您有一个使用大量前端编码的应用程序,您只需编写一次模板。Mustache 模板可以在 PHP、Javascript、Ruby、Scala、甚至是 C++ 中渲染!如果您想转移到或从其他框架(Rails、Grails、Lithium 等)迁移,您可以确信您的视图和设计不需要重新构建。
对于可扩展性,当需要时,您可以使用更强大的引擎(如 Scala)的模板,或者只是从任何来源发送 JSON,然后用 Javascript 渲染。
安装
1. 从应用程序目录 - git submodule add git@github.com:electblake/CakePHP-Mustache-Plugin.git Plugin/Mustache
2. 进入 Plugin/Mustache 目录(以便将最新的 Mustache PHP 实现拖入 Plugin/Mustache/Vendor)
3. git submodule init
4. git submodule update
如果您想全局添加 Mustache 支持,请将其添加到您的 AppController
class AppController extends Controller {
...
public $helpers = array('Mustache.Mustache');
...
}
用法
查看 Mustache 手册:http://mustache.github.com/
创建 Mustache 模板
您的 Mustache 模板都应该放在 /app/View/Elements/
目录中,具有 .mustache
扩展名。
/app/View/Elements/post.mustache
{{#Post}}
<h2>{{title}}</h2\>
<div>
{{text}}
</div>
{{/Post}}
渲染 Mustache 模板
所有由控制器设置的变量都可用,并与传递给 $params
的值合并。
$params = array(
'title' => 'Show me the bacon!',
'text' => 'Bacon ipsum dolor sit amet fatback pig swine...'
);
$this->Mustache->render('template_name', $params)
使用局部模板
局部模板应遵循相同的命名约定。Mustache 将将变量传递给局部模板,它在调用时的上下文中。例如,一个嵌套的用于博客 post
有 comments
的模板可能看起来像
/app/View/Elements/posts/post.mustache
{{#Post}}
<h2>{{title}}</h2\>
<div>
{{text}}
</div>
{{/Post}}
{{#Comment}}
{{>post/comment}}
{{/Comment}}
/app/View/Elements/posts/comment.mustache
<div>
<h3>{{#User}}{{name}}{{/User}} said: </h3>
<p>{{text}}</p>
</div>