PHP code example of guimauve / craft-twig-view-composers
1. Go to this page and download the library: Download guimauve/craft-twig-view-composers library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
guimauve / craft-twig-view-composers example snippets
/**
* 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;
}
}
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();
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.