guimauve / craft-twig-view-composers
该包的最新版本(0.0.1)没有提供许可信息。
允许在页面视图渲染之前调用可组合的PHP类,从而允许像Laravel视图组合器一样组织代码。
0.0.1
2023-06-01 14:16 UTC
Requires
- php: >=8.0.2
- craftcms/cms: ^4.4.0
README
允许在页面视图渲染之前调用可组合的PHP类,从而允许像Laravel视图组合器一样组织代码。
配置
安装插件
composer require guimauve/craft-twig-view-composer
php craft plugin/install _twig-view-composers
然后,将以下路径添加到你的 composer.json 中的 composer 自动加载器。你可以随意命名第二个部分,即psr-4将要查找的目录。
"autoload": {
"psr-4": {
"guimauve\\composers\\": "composers/"
}
},
在该文件夹中,你现在可以创建一个简单的PHP类,名称根据你的twig模板命名,并包含一个"compose"方法。你将接收TemplateEvent作为单个参数。你现在可以向模板数据中添加任何内容,从而隔离功能,例如数据库调用,而无需在模板中执行。
<?php /** * Basic view composer for the templates/index.twig file. * To create a view composer for a subfolder, simply replicate the structure here. * Ex.: templates/blog/_entry.twig -> composers/blog/Entry.php * * Element queries are made with PHP to * avoid using their twig counterparts * @see https://craftcms.com/docs/4.x/element-queries.html */ namespace guimauve\composers; use craft\events\TemplateEvent; use craft\elements\Entry; use Craft; class Index { /** * @param TemplateEvent $event Object passed by View::EVENT_BEFORE_RENDER_TEMPLATE * @see https://github.com/craftcms/cms/blob/a1b232ea1888f131bb7626a5bdaff0f5fa2f4469/src/web/View.php#L1891 * @see https://github.com/craftcms/cms/blob/2eac9249964ccc553bf841c79b9ee44d58f16b61/src/events/TemplateEvent.php * * @return void */ public static function compose(TemplateEvent $event) { $locations = Entry::find()->section('shop')->relatedTo($selectedCity)->with([ [ 'featuredImage', ['withTransforms' => ['x870']] ] ])->collect(); $event->variables['locations'] = $locations; } }
如果你使用基于块的系统,并希望在多个模板或页面上调用相同的代码,很遗憾目前还没有将一个视图组合器绑定到多个模板的方法(尚未实现),但你可以使用PHP Trait来使大部分代码可重用。
namespace guimauve\composers\traits; use Craft; use craft\helpers\App; trait blockableTrait { public static function getBlocksContent() { /** * Do your thing */ } }
在你的视图组合器中
namespace guimauve\composers; use craft\events\TemplateEvent; use craft\elements\Entry; use Craft; class Index { use \guimauve\composers\traits\blockableTrait; /** * @param TemplateEvent $event Object passed by View::EVENT_BEFORE_RENDER_TEMPLATE * @see https://github.com/craftcms/cms/blob/a1b232ea1888f131bb7626a5bdaff0f5fa2f4469/src/web/View.php#L1891 * @see https://github.com/craftcms/cms/blob/2eac9249964ccc553bf841c79b9ee44d58f16b61/src/events/TemplateEvent.php * * @return void */ public static function compose(TemplateEvent $event) { $event->variables['blocks'] = self::getBlocksContent(); } }
要求
此插件需要Craft CMS 4.4.0或更高版本,以及PHP 8.0.2或更高版本。