1️⃣ Изменить Twig-шаблон главной страницы (index.html.twig).
2️⃣ Загрузить товары в контроллере (если нужно кастомное поведение).
3️⃣ Использовать встроенные функции загрузки товаров в Twig.
Создаём кастомный контроллер
📂 src/Controller/LatestProductsController.php
namespace App\Controller;
use Shopware\Core\Content\Product\SalesChannel\Listing\ProductListingLoader;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class LatestProductsController extends AbstractController
{
private ProductListingLoader $productListingLoader;
public function __construct(ProductListingLoader $productListingLoader)
{
$this->productListingLoader = $productListingLoader;
}
public function latestProducts(Request $request, SalesChannelContext $context): Response
{
$criteria = new Criteria();
$criteria->setLimit(20);
$criteria->addSorting(new FieldSorting('createdAt', FieldSorting::DESCENDING));
$result = $this->productListingLoader->load($criteria, $context);
return $this->renderStorefront('@Storefront/storefront/page/home/latest-products.html.twig', [
'products' => $result->getEntities()
]);
}
}
📌 Что здесь происходит?
Загружаем 20 последних товаров по дате (createdAt DESC).
Отправляем их в Twig-шаблон latest-products.html.twig.
Создаём шаблон latest-products.html.twig
📂 src/Resources/views/storefront/page/home/latest-products.html.twig
<div class="container">
<h2>Последние товары</h2>
<div class="product-list grid">
{% for product in products %}
{% sw_include '@Storefront/storefront/component/product/card/box.html.twig' with { 'product': product } %}
{% endfor %}
</div>
</div>
Подключаем контроллер в index.html.twig
📂 src/Resources/views/storefront/page/home/index.html.twig
Добавляем вызов контроллера:
{% block base_main_inner %}
{{ parent() }}
{% block home_latest_products %}
{{ controller('App\\Controller\\LatestProductsController::latestProducts') }}
{% endblock %}
{% endblock %}
🔥 Итог
✅ Если товары уже загружаются – используем listing.elements|slice(0, 20).
✅ Если товаров нет – создаём контроллер и загружаем их вручную.
✅ Подключаем стандартный шаблон карточки товара Shopware.
Теперь главная страница будет показывать 20 последних товаров! 🚀
Комментариев нет:
Отправить комментарий