Вывод номера итерации в сниппете

Как получить номер итерации снипета. Интересует в сниппете getPageAssets компонента Asset Manager. [[+idx]] там не работает. Каким образом можно получить номер итерации в tpl?
КА
26 февраля 2021, 18:16
modx.pro
770
0

Комментарии: 9

Артур Шевченко
26 февраля 2021, 23:41
0
Мне кажется это не очень популярное дополнение в наших краях, поэтому я бы рекомендовал залезть в код сниппета и посмотреть что там, можно попробовать вывод с пустым шаблоном, возможно, он покажет все доступные плейсхолдеры и среди них найдётся подходящий.
    КА
    27 февраля 2021, 11:29
    0
    Да я заметил не особо популярный. Но нужны для ресурса изображения, а это самое подходящее из всего что нашлось.
    Полазил в сниппете но к сожалению не такой профи программист, чтобы разобраться как в цикле вывести номера. Смог только установить плейсхолдер с общим количеством элементов.
      Артур Шевченко
      27 февраля 2021, 11:44
      0
      Скинь код сниппета
        КА
        27 февраля 2021, 23:40
        0
        <?php
        /**
         * @name getPageAssets
         * @description Returns a list of images or other assets for the given page
         *
         * 
         * USAGE EXAMPLES
         *
         * You can use the resize output filter to display different sizes. 
         *
         *  [[getPageAssets? &innerTpl=`<li><img src="[[+asset_id:resize=`300x500`]]" width="300" height="500" alt="[[+Asset.alt]]" /></li>`]]
         *
         * If using the "resize" output filter, you MUST call the snippet cached! Otherwise the "resize" filter attempts to operate on the placeholder
         * before it's set!
         *
         * No results: use a MODX output filter:
         *
         *  [[getPageAssets:empty=`No images found`? ]]
         
         * Available Placeholders
         * ---------------------------------------
         * e.g. to format the original image: 
         *      <img src="[[+Asset.url]]" width="[[+Asset.width]]" height="[[+Asset.height]]" alt="[[+Asset.alt]]" />
         * or the standard Thumbnail:
         *      <img src="[[+Asset.thumbnail_url]]" width="[[+Asset.thumbnail_width]]" height="[[+Asset.thumbnail_height]]" alt="[[+Asset.alt]]" />
         *
         * If needed, include the System Settings (double ++) :
         *      [[++assman.thumbnail_width]]
         *      [[++assman.thumbnail_height]]
         * e.g. <img src="[[+Asset.thumbnail_url]]" width="[[++assman.thumbnail_width]]" height="[[++assman.thumbnail_width]]" alt="[[+Asset.alt]]"/>
         * 
         * 
         *
         *
         * Parameters
         * -----------------------------
         * @param integer $page_id of the page whose images you want. Defaults to the current page.
         * @param string $outerTpl Format the Outer Wrapper of List (Optional)
         * @param string $innerTpl Format the Inner Item of List
         * @param string $firstTpl Format the first Item of List (optional : defaults to innerTpl)
         * @param string $lastTpl Format the last Item of List (optional : defaults to innerTpl)
         * @param string $onOne which tpl to use if there is only 1 result: innerTpl, firstTpl, or lastTpl. Default: innerTpl
         * @param string $group optional: limit the results to the specified group
         * @param boolean $is_active Get all active records only
         * @param boolean $is_image if true, return only images, if false, only other assets. If not set, we get everything.
         * @param int $limit Limit the records to be shown (if set to 0, all records will be pulled)
         * @param string $sort which column should we sort by?  Default: Product.seq
         * @param string $dir which direction should results be returned?  ASC or DESC (optional)
        
         *
         * Variables
         * ---------
         * @var $modx modX
         * @var $scriptProperties array
         *
         * Usage
         * ------------------------------------------------------------
         * To get all Images on certain page
         * [[!getPageAssets? &page_id=`[[*id]]` &outerTpl=`sometpl` &innerTpl=`othertpl` &firstCLass=`first` &is_active=`1` &limit=`0`]]
         * [[!getPageAssets? &page_id=`[[*id]]` &outerTpl=`sometpl` &innerTpl=`othertpl` &is_active=`1` &limit=`1`]]
         *
         * @package assman
         */
        
        $core_path = $modx->getOption('assman.core_path', null, MODX_CORE_PATH.'components/assman/');
        require_once $core_path .'vendor/autoload.php';
        $Snippet = new \Assman\Snippet($modx);
        $Snippet->log('getProductImages',$scriptProperties);
        
        
        // Formatting Arguments:
        $innerTpl = $modx->getOption('innerTpl', $scriptProperties, '<li><img src="[[+Asset.url]]" width="[[+Asset.width]]" height="[[+Asset.height]]" alt="[[+Asset.alt]]" /></li>', true);
        $outerTpl = $modx->getOption('outerTpl', $scriptProperties, '<ul>[[+content]]</ul>', true);
        $firstTpl = $modx->getOption('firstTpl', $scriptProperties, $innerTpl, true);
        $lastTpl = $modx->getOption('lastTpl', $scriptProperties, $innerTpl, true);
        $onOne = $modx->getOption('onOne', $scriptProperties, 'innerTpl', true);
        $sort = $modx->getOption('sort', $scriptProperties, '`PageAsset`.`seq`', true);
        $dir = $modx->getOption('dir', $scriptProperties);
        
        // Default Arguments:
        $scriptProperties['is_active'] = (bool) $modx->getOption('is_active',$scriptProperties, 1);
        $scriptProperties['limit'] = (int) $modx->getOption('limit',$scriptProperties, null);
        $page_id = (int) $modx->getOption('page_id',$scriptProperties);
        
        // Just being safe in case this is run without a resource in context
        if (!$page_id) {
            if (isset($modx->resource) && is_object($modx->resource)) {
                $page_id = $modx->resource->get('id');
            }
        }
        
        if (!$page_id) {
            return 'Page ID is required.';
        }
        
        $criteria = array();
        $criteria['page_id'] = $page_id;
        $criteria['PageAsset.is_active'] = true;
        if (isset($scriptProperties['is_image']) && $scriptProperties['is_image'] !== '') {
            $criteria['Asset.is_image'] = (bool) $scriptProperties['is_image'];
        }
        if (isset($scriptProperties['group']) && $scriptProperties['group'] !== '') {
            $criteria['PageAsset.group'] = $scriptProperties['group'];
        }
        
        $c = $modx->newQuery('PageAsset');
        $c->where($criteria);
        if ($sort && $dir) {
            $c->sortby($sort,$dir);
        }
        elseif($sort) {
            $c->sortby($sort);
        }
        if ($scriptProperties['limit']) {
            $c->limit($scriptProperties['limit']);
        }
        
        $PageAsset = $modx->getCollectionGraph('PageAsset','{"Asset":{}}', $c);
        $cnt = count($PageAsset);
        
        if ($PageAsset) {
            return $Snippet->format($PageAsset,$innerTpl,$outerTpl,$firstTpl,$lastTpl,$onOne,$cnt);
        }
        
        $modx->log(\modX::LOG_LEVEL_DEBUG, "No results found",'','getPageAssets',__LINE__);
        
        return;
          Артур Шевченко
          28 февраля 2021, 00:25
          0
          Судя по сниппету итераций нет, есть метод format и вероятно итерации в нём, а сам метод определен очевидно в классе, значит надо смотреть что там.
            КА
            28 февраля 2021, 12:46
            0
            Да все верно, и цикл я нашел. Но вот передать отсюда $i в шаблон не хватает знаний
            public function format($records,$innerTpl,$outerTpl=null,$firstTpl=null,$lastTpl=null,$onOne='innerTpl',$cnt=0) {
                    if (empty($records)) {
                        return '';
                    }
            
                    // A Chunk Name was passed
                    $use_tmp_chunk = false;
                    if (!$innerChunk = $this->modx->getObject('modChunk', array('name' => $innerTpl))) {
                        $use_tmp_chunk = true;
                    }
            
                    $out = '';
                    $i = 1;
                    foreach ($records as $r) {
                        if (is_object($r)) $r = $r->toArray('',false,false,true); // Handle xPDO objects
                        if ($cnt == 1) {
                            // Real Chunk
                            if ($singleChunk = $this->modx->getObject('modChunk', array('name' => $$onOne))) {
                                $out .= $this->modx->getChunk($$onOne, $r);
                            }
                            // Formatting String
                            else {
                                $uniqid = uniqid() . $i;
                                $singleChunk = $this->modx->newObject('modChunk', array('name' => "{tmp-inner}-{$uniqid}"));
                                $singleChunk->setCacheable(false);    
                                $out .= $singleChunk->process($r, $$onOne); // <-- gulp.
                            }
                            break;
                        }
                        // First
                        if ($i == 1) {
                            // Real Chunk
                            if ($singleChunk = $this->modx->getObject('modChunk', array('name' => $firstTpl))) {
                                $out .= $this->modx->getChunk($firstTpl, $r);
                            }
                            // Formatting String
                            else {
                                $uniqid = uniqid() . $i;
                                $singleChunk = $this->modx->newObject('modChunk', array('name' => "{tmp-inner}-{$uniqid}"));
                                $singleChunk->setCacheable(false);    
                                $out .= $singleChunk->process($r, $firstTpl);                    
                            }          
                        }
                        // Last
                        elseif ($i == $cnt) {
                            // Real Chunk
                            if ($singleChunk = $this->modx->getObject('modChunk', array('name' => $lastTpl))) {
                                $out .= $this->modx->getChunk($lastTpl, $r);
                            }
                            // Formatting String
                            else {
                                $uniqid = uniqid() . $i;
                                $singleChunk = $this->modx->newObject('modChunk', array('name' => "{tmp-inner}-{$uniqid}"));
                                $singleChunk->setCacheable(false);    
                                $out .= $singleChunk->process($r, $lastTpl);                    
                            }            
                        }
                        else {
                            // Use a temporary Chunk when dealing with raw formatting strings
                            if ($use_tmp_chunk) {
                                $uniqid = uniqid() . $i;
                                $innerChunk = $this->modx->newObject('modChunk', array('name' => "{tmp-inner}-{$uniqid}"));
                                $innerChunk->setCacheable(false);    
                                $out .= $innerChunk->process($r, $innerTpl);
                            }
                            // Use getChunk when a chunk name was passed
                            else {
                                $out .= $this->modx->getChunk($innerTpl, $r);
                            }
                        }
                        $i++;
                    }
                    
                    if ($outerTpl) {
                        $props = array('content'=>$out);
                        // Formatting String
                        if (!$outerChunk = $this->modx->getObject('modChunk', array('name' => $outerTpl))) {  
                            $uniqid = uniqid();
                            $outerChunk = $this->modx->newObject('modChunk', array('name' => "{tmp-outer}-{$uniqid}"));
                            $outerChunk->setCacheable(false);    
                            return $outerChunk->process($props, $outerTpl);        
                        }
                        // Chunk Name
                        else {
                            return $this->modx->getChunk($outerTpl, $props);
                        }
                    }
                    return $out;
                }
              Артур Шевченко
              28 февраля 2021, 13:07
              1
              +1
              Напишите
              foreach ($records as $r) {
                if (is_object($r)) $r = $r->toArray('',false,false,true);
                $r['idx'] = $i;
              ...
              После этого по идее в чанке должен появиться плейсхолдер idx;
                КА
                28 февраля 2021, 18:09
                0
                Супер спасибо! idx появился. Работает все как надо.
Авторизуйтесь или зарегистрируйтесь, чтобы оставлять комментарии.
9