memdev / silverstripe-templatehooks
TemplateHooks 允许开发者在 SilverStripe 模板文件中用户(=开发者)定义的钩点处进行钩接。
1.0.1
2016-04-21 20:52 UTC
Requires
- silverstripe/framework: ~3.1
This package is not auto-updated.
Last update: 2024-09-26 01:53:33 UTC
README
一个简单的 SilverStripe 模板钩子系统。
有时扩展或覆盖模板不够,或者会产生大量重复的标记。也许你只想在模板文件中的特定点注入一些标记。这正是模板钩子的作用。
使用模板钩子,你可以在 SilverStripe 模板文件的任何地方添加命名的“注入点”,并在控制器或数据对象中对其进行钩接。
要求
- silverstripe/framework 3.1+
安装
$ composer require memdev/silverstripe-templatehooks
您需要在网站的 URL 后追加 ?flush=1
来执行刷新。
用法
要将钩接点添加到模板中,只需调用 $TemplateHook()
,并提供一个名称作为第一个参数
<div> <nav class="primary"> <span class="nav-open-button">²</span> <ul> <% loop $Menu(1) %> <li class="$LinkingMode"><a href="$Link" title="$Title.XML">$MenuTitle.XML</a></li> <% end_loop %> $TemplateHook('MainNavigation') </ul> </nav> $TemplateHook('AfterMainNavigation') </div>
您可以在控制器或数据对象中调用 hookInto()
来订阅此钩接
class Page_Controller extends ContentController implements TemplateHooks { /** * Use this method to globally subscribe to template hooks. * If you wish to subscribe to hooks in the current controller / object scope, * call "hookInto()" from within any other method, e.g. the controllers init() method. */ public function initHooks() { $this->hookInto('MainNavigation', function($hook) { return SSViewer::execute_template('MyNavigationAppendix', array()); }); } public function init() { parent::init(); $this->hookInto('AfterMainNavigation', array($this, 'AfterMainNavigationHook')); // OR $self = $this; $this->hookInto('AfterMainNavigation', function($hook) use ($self) { return "You are currently reading page {$self->Title}"; }); } public function AfterMainNavigationHook($hook) { return "You are currently reading page {$this->Title}"; } }
您还可以通过模板钩子传递参数
<% loop $Menu(1) %> <li class="$LinkingMode"> <a href="$Link" title="$Title.XML"> $TemplateHook('MainNavItem', $ID) $MenuTitle.XML </a> </li> <% end_loop %>
这些参数将在您的订阅函数中可用
$this->hookInto('MainNavItem', function($hook, $id) { $page = Page::get()->byID($id); // your code here }
文档
待办事项
报告问题
请 创建问题,报告您发现的任何错误或缺少的功能。