Hi!!
I’m having a weird issue with view composers on Sage10. I have a blade view template that is located here:
resources/views/woocommerce/category-products.blade.php
with this content (to simplify things a bit I’ve exposed the title only)
<section class="category-products">
<h2 class="product-category__title">{{ $title }}</h2>
</section>
What I’m trying to do is to loop through Woocommerce categories and show some info and some products from each category. I’m calling that blade template as this from another blade:
@foreach ($product_categories as $category)
@include('woocommerce.category-products', ['category_id' => $category['id']])
@endforeach
The problem is that I’ve created a composer view named CategoryProducts here:
app/View/Composers/CategoryProducts.php
That has this content:
<?php
namespace App\View\Composers;
use Roots\Acorn\View\Composer;
class CategoryProducts extends Composer
{
/**
* List of views served by this composer.
*
* @var array
*/
protected static $views = [
'woocommerce.category-products',
];
/**
* Data to be passed to view before rendering.
*
* @return array
*/
public function with()
{
return [
'title' => $this->title(),
];
}
/**
* Return the category title
*
* @return array
*/
public function title(){
$category_id = $this->data->get('category_id');
if ( $category_id == null ) {
return [];
}
$category = get_term_by('id', $category_id, 'product_cat');
return $category ? $category->name : '';
}
}
Ok, so, the problem is that if the name of the Composer View is CategoryProducts, the Composer is not fired and no info is passed to the view, but if I change it to something like Test then it works
I mean, the previous code doesn’t work (the $title var is not populated so I get the error that $title doesn’t exist), but this does work:
app/View/Composers/Test.php
That has this content:
<?php
namespace App\View\Composers;
use Roots\Acorn\View\Composer;
class Test extends Composer
{
/**
* List of views served by this composer.
*
* @var array
*/
protected static $views = [
'woocommerce.category-products',
];
/**
* Data to be passed to view before rendering.
*
* @return array
*/
public function with()
{
return [
'title' => $this->title(),
];
}
/**
* Return the category title
*
* @return array
*/
public function title(){
$category_id = $this->data->get('category_id');
if ( $category_id == null ) {
return [];
}
$category = get_term_by('id', $category_id, 'product_cat');
return $category ? $category->name : '';
}
}
These are my composer.json required packages:
"require": {
"php": "^7.3|^8.0",
"generoi/sage-woocommerce": "dev-master",
"log1x/acf-composer": "^1.5",
"log1x/sage-directives": "^1.1",
"log1x/sage-html-forms": "^1.0",
"log1x/sage-svg": "^1.0",
"roots/acorn": "dev-main"
},
Anyone has some hints to guide me up to solve the problem. I know the solution is to name it with a different name but I want to be sure why is this happening.
Thank you!!