app-verk / block-bundle

AppVerk block bundle

安装量: 3,236

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 3

分支: 0

公开问题: 0

类型:symfony-bundle

v1.0 2018-06-12 09:33 UTC

This package is auto-updated.

Last update: 2024-09-15 23:17:41 UTC


README

Symfony Block Bundle

配置

使用 composer 安装包

$ composer require app-verk/block-bundle

在 kernel 中启用包

<?php
// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new AppVerk\BlockBundle\BlockBundle(),
        // ...
    );
}

Twig 辅助函数

渲染块

{{ render_block(block_id) }}

带选项渲染块

{{ render_block(block_id, {
    'template': 'BlockBundle:Block:sample.html.twig'
}) }}

创建块

记得扩展 AppVerk\BlockBundle\Block\AbstractBlock。

<?php

namespace AppBundle\Block;

use AppVerk\BlockBundle\Block\AbstractBlock;
use Symfony\Component\OptionsResolver\OptionsResolver;

class HelloBlock extends AbstractBlock
{
    protected function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);

        $resolver->setDefaults([
            'template' => 'AppBundle:Block:hello.html.twig',
            'message'  => null
        ]);
    }
}

块应设置为公共服务或具有别名。

services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false

    AppBundle\:
        resource: '../../*'
        exclude: '../../{Entity,Repository,Tests,Doctrine,Twig}'

    AppBundle\Block\HelloBlock:
        public: true

在 Twig 中执行

{{ render_block('AppBundle\\Block\\HelloBlock', {
    'template': 'AppBundle:Block:hello.html.twig',
    'message': 'Hello there!'
}) }}

更复杂的块可以覆盖 execute 方法,例如使用 EntityManager。

<?php

namespace AppBundle\Block;

use AppBundle\Entity\Product;
use AppVerk\BlockBundle\Block\AbstractBlock;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityNotFoundException;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ProductBlock extends AbstractBlock
{
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;


    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    protected function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);

        $resolver->setDefaults([
            'template' => 'AppBundle:Block:product.html.twig',
            'slug'     => ''
        ]);
    }

    public function execute(array $options = [])
    {
        $settings = $this->getSettings($options);

        $entity = $this->entityManager->getRepository(Product::class)->findOneBy([
            'slug' => $settings['slug']
        ]);
        if (!$entity) {
            throw new EntityNotFoundException();
        }

        return $this->renderResponse($settings['template'], [
            'settings' => $settings,
            'entity'   => $entity
        ]);
    }
}

许可证

此包在 MIT 许可证 下发布。