Bitrix

Проблема вызова хлебных крошек в шаблонах компонентов

Если в код шаблона компонента внедрить вызов компонента хлебных крошек, то часть кода, включающая сами хлебные крошки и код до него, отобразится только один раз. Далее будет показываться сломанный код.

Проблему можно решить, выводя в шаблоне какой-то плейсхолдер, а в component_epilog.php заменять плейсхолдер на код хлебных крошек. Эта задача решается при помощи дополнительного класса ComponentHelper.

Код класса ComponentHelper (взят с https://habr.com/ru/sandbox/115802/):

<?php
#/bitrix/php_interface/classes/ComponentHelper.php
namespace PHPInterface;

/**
 * ComponentHelper
 *
 * Создает плейсхолдеры в шаблоне
 * При помощи статической функции handle обрабатывает их
 * Класс необходим для вызова некешируемых функций
 */
class ComponentHelper
{
    private $component = null;
    private $lastPlIndex = 0;
    private $pull = array();

    public function __construct(\CBitrixComponent $component)
    {
        $this->component = $component;
        $this->component->SetResultCacheKeys(array('CACHED_TPL', 'CACHED_TPL_PULL'));
        ob_start();
    }

    public function deferredCall($callback, $args = array())
    {
        $plName = $this->getNextPlaceholder();
        echo $plName;
        $this->pull[$plName] = array('callback' => $callback, 'args' => $args);
    }

    public function saveCache()
    {
        $this->component->arResult['CACHED_TPL'] = @ob_get_contents();
        $this->component->arResult['CACHED_TPL_PULL'] = $this->pull;
        ob_get_clean();
        $this->component = null;
    }

    private function getNextPlaceholder()
    {
        return '##PLACEHOLDER_'.(++$this->lastPlIndex).'##';
    }

    public static function handle(\CBitrixComponent $component)
    {
        $buf = &$component->arResult['CACHED_TPL'];
        foreach ($component->arResult['CACHED_TPL_PULL'] as $plName => $params) {
            list($prevPart, $nextPart) = explode($plName, $buf);
            echo $prevPart;
            call_user_func_array($params['callback'], $params['args']);
            $buf = &$nextPart;
        }
        echo $buf;
    }
}

Далее в шаблоне компонента пишем:

$helper = new PHPInterface\ComponentHelper($component);
$helper->deferredCall('ShowNavChain', array('.default'));
//...
// И в конце шаблона обязательно вызвать 
$helper->saveCache();

Добавляем в init.php такую функцию:

function ShowNavChain($template = ‘.default’) {

global $APPLICATION;

$APPLICATION->IncludeComponent(«bitrix:breadcrumb», «», Array( «START_FROM» => «0», «PATH» => «», «SITE_ID» => «s1» ) );

}

А в component_epilog.php шаблона добавляем такой код:

PHPInterface\ComponentHelper::handle($this);

Отставить комментарий

Ваш электронный адрес не будет опубликован.Обязательные для заполнения поля отмечены *

один + четырнадцать =