---
metadata:
  - name: generator
    content: Diplodoc Platform v5.39.1
alternate:
  - https://yandex.com.tr/dev/jsapi-v2-1/doc/en/v2-1/examples/cases/cluster_custom_balloon_content_layout.md
  - https://yandex.com.tr/dev/jsapi-v2-1/doc/ru/v2-1/examples/cases/cluster_custom_balloon_content_layout.md
---
> **Documentation Index:** Fetch the complete configuration index at https://yandex.com.tr/dev/jsapi-v2-1/doc/ru/llms.txt

# Собственный макет балуна кластера

<iframe id="LIVE-EXAMPLE" style="width:100%;height: 400px;border-radius: 8px;border: 1px solid rgba(92, 94, 102, 0.14);" frameBorder="0" src="https://yastatic.net/s3/front-maps-static/maps-front-jsapi-v2-1/examples/2/out/s3-cases/ru/cluster_custom_balloon_content_layout/index.html" allow="fullscreen"></iframe>

<a target="_blank" rel="noopener noreferrer" style="display: inline-block;margin-top: 10px;cursor: pointer;border-radius: 4px;padding: 9px 12px;background: #151515;color: white;text-decoration: none;font-weight: 500" href="https://codesandbox.io/p/sandbox/cx6trk?file=index.html">Open in CodeSandbox</a>

<div id="references">
    <a href="https://yandex.ru/dev/jsapi-v2-1/doc/ru/v2-1/ref/reference/ready">ready</a>, <a href="https://yandex.ru/dev/jsapi-v2-1/doc/ru/v2-1/ref/reference/Map">Map</a>,
    <a href="https://yandex.ru/dev/jsapi-v2-1/doc/ru/v2-1/ref/reference/Clusterer">Clusterer</a>, <a href="https://yandex.ru/dev/jsapi-v2-1/doc/ru/v2-1/ref/reference/ClusterPlacemark">ClusterPlacemark</a>, <a href="https://yandex.ru/dev/jsapi-v2-1/doc/ru/v2-1/ref/reference/templateLayoutFactory">templateLayoutFactory</a>,
    <a href="https://yandex.ru/dev/jsapi-v2-1/doc/ru/v2-1/ref/reference/Placemark">Placemark</a>
</div>
    В данном примере создается собственный макет контента балуна кластера.<br/>
    Макет задается опцией 'clusterBalloonContentLayout'.
<br/>
    <a href="https://yandex.ru/dev/jsapi-v2-1/doc/ru/v2-1/dg/concepts/layouts">Макеты</a>
    объектов можно создавать с помощью фабрики <a href="https://yandex.ru/dev/jsapi-v2-1/doc/ru/v2-1/ref/reference/templateLayoutFactory">templateLayoutFactory</a>,
    используя текстовые шаблоны. <br/>
    Текстовые шаблоны формируют html-содержимое макета на основе хэша с данными,
    передаваемого в конструктор макета.<br/>
    В данном примере поставщиком данных является кластер, у которого был открыт балун.<br/>
<br/>
    В макете происходит перечисление и вывод полей 'placemarkId' и 'balloonContentHeader' всех геообъектов кластера при помощи конструкции 'for'.

{% list tabs %}

-   index.html

    ```html
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
        <html>
            <head>
                <title>Собственный макет балуна кластера</title>
                <meta
                    http-equiv="Content-Type"
                    content="text/html; charset=UTF-8"
                />
                
                <!--
            Укажите свой API-ключ. Тестовый ключ НЕ БУДЕТ работать на других сайтах.
            Получить ключ можно в Кабинете разработчика: https://developer.tech.yandex.ru/keys/
        -->
                
                
                
            </head>
            <body>
                <div id="map"></div>
            </body>
        </html>
    </html>
    ```

-   cluster_custom_balloon_content_layout.js

    ```js
    jQuery(function () {
        ymaps.ready(function () {
            var mapCenter = [55.755381, 37.619044],
                map = new ymaps.Map("map", {
                    center: mapCenter,
                    zoom: 10,
                    controls: [],
                }),
                placemarks = [];

            // Создаем собственный макет с информацией о выбранном геообъекте.
            var customBalloonContentLayout =
                ymaps.templateLayoutFactory.createClass(
                    [
                        "<ul class=list>",
                        // Выводим в цикле список всех геообъектов.
                        "{% for geoObject in properties.geoObjects %}",
                        '<li><a href=# data-placemarkid="{{ geoObject.properties.placemarkId }}" class="list_item">{{ geoObject.properties.balloonContentHeader|raw }}</a></li>',
                        "{% endfor %}",
                        "</ul>",
                    ].join("")
                );

            jQuery(document).on("click", "a.list_item", function () {
                // Определяем по какой метке произошло событие.
                var selectedPlacemark =
                    placemarks[jQuery(this).data().placemarkid];
                alert(selectedPlacemark.properties.get("balloonContentBody"));
            });

            var clusterer = new ymaps.Clusterer({
                clusterDisableClickZoom: true,
                clusterOpenBalloonOnClick: true,
                // Устанавливаем режим открытия балуна.
                // В данном примере балун никогда не будет открываться в режиме панели.
                clusterBalloonPanelMaxMapArea: 0,
                // По умолчанию опции балуна balloonMaxWidth и balloonMaxHeight не установлены для кластеризатора,
                // так как все стандартные макеты имеют определенные размеры.
                clusterBalloonMaxHeight: 200,
                // Устанавливаем собственный макет контента балуна.
                clusterBalloonContentLayout: customBalloonContentLayout,
            });

            // Заполняем кластер геообъектами со случайными позициями.
            for (var i = 0, l = 100; i < l; i++) {
                var placemark = new ymaps.Placemark(getRandomPosition(), {
                    // Устаналиваем данные, которые будут отображаться в балуне.
                    balloonContentHeader: "Заголовок метки №" + (i + 1),
                    balloonContentBody: "Информация о метке №" + (i + 1),
                    placemarkId: i,
                });
                placemarks.push(placemark);
            }

            clusterer.add(placemarks);
            map.geoObjects.add(clusterer);

            function getRandomPosition() {
                return [
                    mapCenter[0] + (Math.random() * 0.3 - 0.15),
                    mapCenter[1] + (Math.random() * 0.5 - 0.25),
                ];
            }
            clusterer.balloon.open(clusterer.getClusters()[0]);
        });
    });
    ```

{% endlist %}
