starychfojtu/viewcomponent

Symfony 3.3 视图组件的实现

安装次数: 1,953

依赖者: 0

建议者: 0

安全: 0

星星: 0

观察者: 1

分支: 1

开放问题: 0

类型:symfony-bundle

v0.4.0 2017-09-25 07:50 UTC

This package is not auto-updated.

Last update: 2024-09-29 03:15:27 UTC


README

Symfony 3.3 视图组件的实现

安装

$ composer require starychfojtu/viewcomponent

Symfony flex 可能会在 bundles.php 中注册错误的命名空间。如果是这样,请自行使用以下方法注册:

'ViewComponent\ViewComponentBundle' => ['all' => true]

配置

starychfojtu_view_component:
    component_dirs: ['AppBundle/Component', 'AppBundle/SpecialComponent'] #results in '/src/AppBundle/Component', '/src/AppBundle/Component/specialComponent'
    # Specify directories where the bundle should search for components from /src
    template_dirs: ['components', 'specialComponents'] #results in '/templates/components', '/templates/specialComponents'
    # Specify directories where the bundle should search for templates from /templates

用法

首先通过在配置的目录中创建一个类来指定您的视图组件,并实现 ViewComponentInterface。渲染方法返回一个对象关联数组,这些对象将被传递到视图中。

您必须按照这种方式命名您的组件:YourSpecialNameViewComponent。它是一个经典的驼峰命名法,例如 MenuViewComponent 或 CartSummaryViewComponent。

# src/AppBundle/Component/MenuViewComponent

<?php

namespace AppBundle\Component;

use Starychfojtu\ViewComponentBundle\ViewComponentInterface;

class MenuViewComponent implements ViewComponentInterface
{
    public function render(): array
    {
        return [
            'links' => ['home','about','contact']
        ];
    }
}

然后,将您的模板添加到配置的目录之一。

# templates/components/Menu.html.twig

{% for link in links %}
    {{ link }}
{% endfor %}

最后在视图中渲染您的组件

{{ component('Menu', 60 * 60) }}

第二个参数是整个组件的缓存时间,默认设置为 0;

自定义模板名称

如果您想在视图组件中指定另一个模板名称,只需添加一个带有模板的键,如下所示

# src/AppBundle/Component/MenuViewComponent

<?php

namespace AppBundle\SpecialComponent;

use Starychfojtu\ViewComponentBundle\ViewComponentInterface;

class MenuViewComponent implements ViewComponentInterface
{
    public function render(): array
    {
        return [
            'links' => ['home','about','contact'],
            'template' => 'AnotherMenu'
        ];
    }
}

依赖注入

要向组件传递任何依赖项,只需将它们注册为服务。

TODO:自动在包中注册它们