Table of contents
- Transform Craft CMS contents to custom data structures
- Create custom Transformer classes for your components
- Cache contents on a Transformer basis (via providing
getCacheKey)
- Craft CMS >= 5.x
1. Install
Install the package
cd /path/to/project
composer require fork/craft-transform2. Configure namespace and create transformers
- Copy the example
config.phpto your Craft config directory and rename it totransform.php - Specify the namespace to your custom Transformer classes (in your project plugin/module). Here's an example:
<?phpreturn [
'*' => [
'transformerNamespace' => '\company\project\transformers'
],
'dev' => [
'enableCache' => false,
],
'staging' => [
'enableCache' => true,
],
'production' => [
'enableCache' => true,
],
];In your project plugin/module create a transformers directory to put your transformers. Here is an example Transformer class:
<?phpnamespacecompany\project\transformers;
useCraft;
useLeague\Fractal\TransformerAbstract;
class FooterTransformer extends TransformerAbstract {
publicfunctiontransform()
{
$footer = Craft::$app->globals->getSetByHandle('footer');
$footerNavGlobals = $footer->footerNavigationElements->all();
$footerLinks = [];
foreach ($footerNavGlobalsas$linkEntry) {
$link = [
'href' => $linkEntry->navigationLink->getUrl(),
'name' => $linkEntry->navigationLink->getText(),
'slug' => $linkEntry->navigationLink->hasElement() ? $linkEntry->navigationLink->getElement()->slug : $linkEntry->navigationLink->getUrl(),
'target' => $linkEntry->navigationLink->getTarget()
];
$footerLinks[] = $link;
}
return$footerLinks;
}
}In your templates you can use craft.transform.getData(). The first parameter is optional. It could be your entry to get the data from.
Also, it could be null. The second parameter must match with the corresponding Transformer class. E.g. pass 'Footer' to use the FooterTransformer.
{% setarticleData= {
headline: entry.title,
contentBlocks: craft.transform.getData(entry, 'ContentBlocks')
} %}
{% include'@components/templates/article-page/article-page.twig'with {
header: craft.transform.getData(null, 'Header'),
headline: articleData.headline,
contentBlocks: articleData.contentBlocks,
footer: craft.transform.getData(null, 'Footer')
} only %}- Caching
- Logo
- Settings maybe (instead of config file)
Brought to you by Fork Unstable Media GmbH
