Объединение TypoScript и Fluid: итерации?

Я комбинирую объект TypoScript CONTENT с гибким шаблоном.

В шаблоне страницы:

<f:cObject typoscriptObjectPath="lib.myItem" />

In TS:

lib.myItem = CONTENT
lib.myItem {
  table = tt_content
  select.where = colPos = 0
  select.languageField = sys_language_uid
  renderObj = FLUIDTEMPLATE
  renderObj {
    file = {$customContentTemplatePath}/Myfile.html
    layoutRootPath = {$customContentLayoutPath}
    partialRootPath = {$customContentPartialPath}
    dataProcessing {
      10 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
      10.references.fieldName = image
    }
  }
}

В Myfile.html:

{namespace v=FluidTYPO3\Vhs\ViewHelpers}

<div class="small-12 medium-6 large-4 columns">
    <f:for each="{files}" as="file">
      <v:media.image src="{file}" srcset="1200,900,600" srcsetDefault="600" alt="{file.alternative}" treatIdAsReference="1"/>
    </f:for>
    <div class="fp-ql-txt">
      {data.header} >
    </div>
</div>

Но теперь я понял, что, поскольку шаблон применяется renderObj для каждого элемента содержимого, у меня нет доступа к информации о каждой итерации для каждой жидкости. Итак, я не могу этого сделать:

  <f:for each="{data}" as="item" iteration="itemIterator">
  {itemIterator.cycle}
  </f:for>

чтобы узнать, в каком из отображаемых элементов мы находимся ... потому что каждый элемент отображается индивидуально с помощью renderObj.

Как я могу получить информацию об итерации продуктов renderObj? Только в TS со старыми и ужасающими счетчиками, как в http://typo3-beispiel.net/index.php?id=9?


person Urs    schedule 29.03.2016    source источник


Ответы (2)


Вы можете создать свой собственный IteratorDataProcessor:

<?php
namespace Vendor\MyExt\DataProcessing;

use TYPO3\CMS\Core\SingletonInterface;
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
use TYPO3\CMS\Frontend\ContentObject\DataProcessorInterface;
use TYPO3\CMS\Frontend\ContentObject\Exception\ContentRenderingException;

/**
 * This data processor will keep track of how often he was called and whether it is an
 * even or odd number.
 */
class IteratorProcessor implements DataProcessorInterface, SingletonInterface
{
    /**
     * @var int
     */
    protected $count = 0;

    /**
     * Process data for multiple CEs and keep track of index
     *
     * @param ContentObjectRenderer $cObj The content object renderer, which contains data of the content element
     * @param array $contentObjectConfiguration The configuration of Content Object
     * @param array $processorConfiguration The configuration of this processor
     * @param array $processedData Key/value store of processed data (e.g. to be passed to a Fluid View)
     * @return array the processed data as key/value store
     * @throws ContentRenderingException
     */
    public function process(ContentObjectRenderer $cObj, array $contentObjectConfiguration, array $processorConfiguration, array $processedData)
    {
        $iterator = [];
        $iterator['index'] = $this->count;
        $iterator['isFirst'] = $this->count === 0;
        $this->count++;
        $iterator['cycle'] = $this->count;
        $iterator['isEven'] = $this->count % 2 === 0;
        $iterator['isOdd'] = !$iterator['isEven'];
        $processedData['iterator'] = $iterator;
        return $processedData;
    }
}

В Typoscript вы передаете свои данные через этот процессор:

dataProcessing {
    10 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
    10 {
        references.fieldName = image
    }
    20 = Vendor\MyExt\DataProcessing\IteratorProcessor
}

В жидкости вы можете получить доступ к тому, что вы установили в своем DataProcessor, например, {iterator.isFirst}.

person Daniel    schedule 29.03.2016
comment
Я полагаю, вы не просто написали это специальное предложение - у вас тоже есть такой вариант использования? Как вы думаете, это верный сценарий? - person Urs; 29.03.2016
comment
Конечно, это является. Я буду использовать этот самый DataProcessor в своем проекте. - person Daniel; 29.03.2016
comment
эхм ... Я поместил его в EXT:template/Classes/DataProcessing/IteratorProcessor.php, поместил в пространство имен STUBR\Template\DataProcessing и назвал renderObj.dataProcessing.20 = STUBR\Template\DataProcessing\IteratorProcessor - что дает мне Исключение Processor class name "STUBR\Template\DataProcessing\IteratorProcessor" does not exist. Нужно ли мне где-то регистрировать DataProcessor? - person Urs; 29.03.2016
comment
Регистрация не требуется. Вам просто нужно убедиться, что ваш класс загружен. :) Беннис тоже отвечает вполне законно. До тех пор, пока вам не нужно добавлять в свой итератор специальные элементы, на которые не способна собственная итерация Fluid, я бы пошел с его подходом. - person Daniel; 01.04.2016

Вы должны проверить DatabaseQueryProcessor, поставляемый с TYPO3 Core.

https://docs.typo3.org/typo3cms/TyposcriptReference/ContentObjects/Fluidtemplate/Index.html#dataprocessing

Обратите внимание, что обработка данных работает только внутри объекта FLUIDTEMPLATE cObject.

Вы также найдете рабочий пример в документации.

person Benni    schedule 30.03.2016
comment
С DatabaseQueryProcessor вместо renderObj итерация была бы уже доступна, верно? - person Urs; 30.03.2016