contextualcode/ezplatform-richtext-template-extension

eZ Platform 组件,允许实现自定义标签/样式的自定义逻辑

v3.0.1 2023-08-31 15:41 UTC

This package is auto-updated.

Last update: 2024-08-30 01:49:36 UTC


README

eZ Platform 组件,允许实现自定义标签/样式的自定义逻辑。

安装

  1. 运行 composer require
     composer require contextualcode/ezplatform-richtext-template-extension
    

用法

假设您有一个 place_info 自定义标签。它有一个 place_location_id 参数。并且 place_info.html.twig 模板用于渲染它。

此自定义标签的配置类似于

ezrichtext:
    custom_tags:
        place_info:
            template: '@ezdesign/field_type/ezrichtext/custom_tag/place_info.html.twig'
            icon: '/bundles/app/img/icons.svg#place_info'
            is_inline: false
            attributes:
                place_location_id:
                    type: 'number'
                    required: true

目前 params.place_location_id 变量在 place_info.html.twig 模板中可用。假设我们需要在模板中有一个位置 Location 对象。为了做到这一点,我们需要遵循以下简单步骤。

1. 创建自定义标签扩展服务类

它需要扩展 ContextualCode\EzPlatformRichTextTemplateExtension\eZ\RichText\Converter\Render\Template\Extension\Base 并实现 extend 方法。它将返回额外的参数,这些参数将可用于自定义标签模板。我们将注入 ezpublish.api.service.location 服务,它将用于加载位置 Location。同时,自定义标签名称需要传递给父构造函数

<?php

namespace AcmeBundle\CustomTagExtension;

use Exception;
use eZ\Publish\API\Repository\LocationService;
use ContextualCode\EzPlatformRichTextTemplateExtension\eZ\RichText\Converter\Render\Template\Extension\Base;

class Location extends Base
{
    /**
     * @var \eZ\Publish\API\Repository\LocationService
     */
    protected $locationService;

    /**
     * @param \eZ\Publish\API\Repository\LocationService
     * @param string $identifier Identifier
     * @param string $type Type: tag or style
     */
    public function __construct(LocationService $locationService, string $identifier, string $type)
    {
        $this->locationService = $locationService;

        parent::__construct($identifier, $type);
    }

    /**
     * Returns additional parameters which will be available in the view.
     * You can use injected services here to get them.
     *
     * @param array $params Current set of parameters
     *
     * @return array
     */
    public function extend(?array $params): array
    {
        if (isset($params['place_location_id']) === false) {
            return [];
        }

        try {
            $location = $this->locationService->loadLocation($params['place_location_id']);
        } catch (Exception $e) {
            return [];
        }

        return ['place_location' => $location];
    }
}

2. 定义自定义标签扩展服务

服务需要具有 ezpublish.ezrichtext.converter.output.template.extension 标签。因此,其定义将类似于

services:
    ezrichtext.converter.template.extensions.accordion:
        class: AcmeBundle\CustomTagExtension\Location
        tags: [ezpublish.ezrichtext.converter.output.template.extension]
        arguments:
            - '@ezpublish.api.service.location'
            - 'location'
            - 'tag'

3. 在模板中使用新参数

就是这样,现在您在 place_info.html.twig 模板中有了 params.place_location 变量。