Сейчас узнаем, какой подарок выпадет именно Вам
Крутите колесо
Как создать хлебные крошки через блок ME605 в Tilda

Как создать хлебные крошки через блок ME605 в Tilda

1
Создали блок ME605 и заполнили как на скрине ниже
2
Важно, что пример работает при соблюдении вложенности при формировании адресов страниц
3
Ставим код в блок Т123
Блоки Т123 и ME605 расположили на
страницах обычного и продуктового header
Mo-ti Level Up
Видео инструкции по добавлению кода и работе с Zero Block.
Как переключать таблички по клику на кнопку в ZeroBlock в Tilda
Фрагмент видео
Библиотека для примера
<script>
(function() {
    'use strict';
    
    const cache = {};
    
    function getLinkText(link) {
        let text = '';
        for (let node of link.childNodes) {
            if (node.nodeType === 3) {
                text += node.textContent;
            } else if (node.nodeType === 1 && !node.matches('img, svg, .crumb-text')) {
                text += node.textContent;
            }
        }
        return text.replace(/[\s\u200B]/g, '').trim();
    }
    
    function isPlaceholder(link) {
        const href = link.getAttribute('href');
        const text = getLinkText(link);
        return (href === '#' || !href) && (text === '#' || text === '');
    }
    
    function getCurrentTitle() {
        const h1 = document.querySelector('h1');
        return (h1?.textContent || document.title || 'Страница').trim();
    }
    
    async function fetchTitle(url) {
        if (cache[url]) return cache[url];
        try {
            const ctrl = new AbortController();
            setTimeout(() => ctrl.abort(), 3000);
            const res = await fetch(url, { signal: ctrl.signal });
            if (!res.ok) throw new Error();
            const html = await res.text();
            const doc = new DOMParser().parseFromString(html, 'text/html');
            const h1 = doc.querySelector('h1');
            const title = (h1?.textContent || doc.title || 'Раздел').trim();
            cache[url] = title;
            return title;
        } catch {
            return 'Раздел';
        }
    }
    
    function updateLink(link, url, title, isLast) {
        const icons = [...link.querySelectorAll('img, svg')];
        link.innerHTML = '';
        icons.forEach(icon => link.appendChild(icon));
        
        const span = document.createElement('span');
        span.className = 'crumb-text';
        span.textContent = title;
        link.appendChild(span);
        
        link.href = isLast ? '#' : url;
        
        if (isLast) {
            link.classList.add('t758__link-item_active');
            link.setAttribute('aria-current', 'page');
        }
    }
    
    function wrapText(link) {
        if (link.querySelector('.crumb-text')) return;
        for (let node of [...link.childNodes]) {
            if (node.nodeType === 3 && node.textContent.trim()) {
                const span = document.createElement('span');
                span.className = 'crumb-text';
                span.textContent = node.textContent;
                link.replaceChild(span, node);
            }
        }
    }
    


    async function init() {
        const container = document.querySelector('[data-record-type="758"]');
        if (!container) return;
        
        const items = [...container.querySelectorAll('.t758__list_item')];
        const links = items.map(i => i.querySelector('.t-menu__link-item')).filter(Boolean);
        if (!links.length) return;
        
        const origin = location.origin;
        const isProductPage = /\/tproduct\//.test(location.pathname);
        
        const cleanPath = isProductPage 
            ? location.pathname.replace(/\/tproduct\/.*/, '') 
            : location.pathname;
        
        const parts = cleanPath.split('/').filter(p => p).map(decodeURIComponent);
        
        let partIndex = 0;
        let usedLinksCount = 0;

        for (let i = 0; i < links.length && partIndex < parts.length; i++) {
            const link = links[i];
            const item = items[i];
            
            if (!isPlaceholder(link)) {
                wrapText(link);
                usedLinksCount++;
                continue;
            }
    
            const currentPath = '/' + parts.slice(0, partIndex + 1).join('/');
            const url = origin + currentPath;
            
            const isLastCategory = !isProductPage && (partIndex === parts.length - 1);
            
            const title = isLastCategory ? getCurrentTitle() : await fetchTitle(url);
            updateLink(link, url, title, isLastCategory);
    

            if (isLastCategory) {
                const divider = item.querySelector('.t758__breadcrumb-divider');
                if (divider) divider.style.display = 'none';
            }
    
            partIndex++;
            usedLinksCount++;
        }
        

        if (isProductPage && usedLinksCount < links.length) {
            const link = links[usedLinksCount];
            const item = items[usedLinksCount];
            
            const productTitle = getCurrentTitle();
            updateLink(link, '#', productTitle, true);
            
        
            const divider = item.querySelector('.t758__breadcrumb-divider');
            if (divider) divider.style.display = 'none';
            
            usedLinksCount++;
        }
        

        for (let i = usedLinksCount; i < items.length; i++) {
            items[i].style.display = 'none';
        }
    
        const block = container.querySelector('.t758');
        if (block) block.style.opacity = '1';
    }

    
    
    
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
</script>

<style>
.t758 {
	opacity: 0;
	transition: opacity 0.2s;
}

.t758__link-item_active {
	font-weight: 600;
	color: #333;
	cursor: default;
	pointer-events: none;
}

.t758__breadcrumb-divider.is-hidden,
.t758__list_item:last-child .t758__breadcrumb-divider {
	display: none !important;
}

.crumb-text {
	display: inline;
}
</style>
Made on
Tilda