Как использовать макросы в Confluence, чтобы систематизировать и оформить документацию по продукту и процессам?
Привет, Хабр! Меня зовут Таня Дудо, и я уже 6 лет помогаю людям и командам обмениваться знаниями внутри компаний. Для этого использую Confluence. Да-да, ту самую wiki-систему, которую часто называют неудобной и несовременной. Сегодня выступлю ее адвокатом-обозревателем: расскажу про 7 полезных макросов для систематизации и оформления контента и наглядно покажу, как они работают.
Дисклеймер: с марта Atlassian не продают лицензии в Россию напрямую. Но если у вас уже есть, никто не запрещает ей пользоваться. На сайте Atlassian есть развернутая документация по установке Confluence и Jira. Она охватывает практически все аспекты. Вот, например, одна из статей.
В чем проблема с Confluence или почему я решила написать этот текст
Часто вижу в разных компаниях, что документация в Confluence живет своей жизнью: команды оформляют и хранят данные как хотят, никто сильно не погружается в работу этой системы. Из-за этого она кажется неповоротливой, вызывает раздражение и жаркие споры о том, какой инструмент лучше подойдет для накопления и передачи знаний.
Не буду утверждать, что Confluence — самый лучший в мире инструмент для работы с документацией. Все-таки, это дело привычки, вкуса и корпоративных ограничений. Наоборот, в тексте сосредоточусь на прикладных знаниях о том, как ласково приручить этого непростого зверя и покажу, как документация может преобразиться с использованием конкретных макросов.
- недавно начал с ней работать,
- уже использует и ищет способы сделать работу с Confluence более комфортной.
Что такое макросы и зачем они нужны
Макросы — это программные алгоритмы действий, «упакованные» в понятный графический интерфейс. Если проще, это внутренние инструменты Confluence, которые помогают делать документацию понятнее и удобнее.
Чем макросы круче текстовых редакторов?
Базовая комплектация текстового редактора выполняет простые операции по редактированию. Например, там можно выделить текст жирным или курсивом, изменить цвет символов, выровнять столбцы по середине или по краю.
Макросы эти возможности расширяют: интегрируют контент из внешних источников, помогают настроить навигацию внутри большой базы знаний или сформировать единый тон визуального оформления документации.
- форматирование контента,
- интеграция внутреннего контента,
- интеграция внешнего контента.
Где находятся макросы
Макросы можно добавить в статью в режиме редактирования. Они прячутся в верхней панели инструментов, за кнопкой с названием «Вставить прочий контент».
Самые популярные макросы — например, «Оглавление» и «Галерея» — лежат в выпадающем меню. Больше возможностей скрываются за строчкой «Другие макросы».
В библиотеке макросы рассортированы по группам. В левой части интерфейса можно сразу перейти к нужной группе.
Если подходящего макроса не нашлось, через кнопку «Найти еще макросы…» можно перейти в Atlassian Market и изучить платные и бесплатные дополнения, совместимые с вашей версией Confluence.
Макросы-блоки и макросы-рамки
Макрос может быть самодостаточным и не требовать вставки чего-то (например, текста, изображений или ссылок) внутри себя. В таком случае он выглядят как блок.
Макросы-блоки выполняют сложные операции вроде составления оглавления, интеграции контента и формирования диаграмм.
Если для работы макроса что-то нужно поместить внутрь, он выглядит как рамка.
Режим редактирования. Внутри рамки макроса — текст, который будет в раскрывающемся меню.
После сохранения страница будет выглядеть так.
Внутрь одного макроса-рамки можно помещать сколько угодно других макросов. Главное, чтобы в пирамиде была логика. Так, например, можно сделать пирамиду из раскрывающихся пунктов, или спрятать содержание статьи, если оно слишком объемное. Или добавить макрос форматирования текста.
Возможно, эти тексты тоже вас заинтересуют:
Макросы форматирования: подсказка, предупреждение, примечание и блок кода
- делают важные текстовые вставки заметными,
- задают единый тон визуального оформления,
- позволяют вставить код в статью и подсветить синтаксис.
Пожалуй, самый распространенный пример разноформатного подхода — это выделение подсказки, предупреждения и примечания.
Опасность разного оформления в том, что при беглом прочтении такие акценты могут проскользнуть мимо внимания читателя. А еще к ним будет сложно вернуться и придется перечитывать текст заново.
Как использовать
В Confluence нашли изящное решение: унифицировали макросы «Подсказка», «Предупреждение», «Примечание» и «Информация».
Описание этой группы макросов в Confluence.
В режиме редактирования они выглядят как макросы-рамки, внутри которых можно разместить текст.
После публикации блоки с выделенной информацией становятся заметнее, и, главное, выглядят однообразно в разных статьях.
Текст до использования макроса:
Текст после. В итоге примечание выглядит аккуратно и имеет необходимый по смыслу визуальный акцент:
Еще один классный макрос, который поможет сделать доку более удобной и читаемой — блок кода. Он не только форматирует текст, но и подсвечивает синтаксис языка, на котором код написан. Кроме того, подходит для размещения небольших отрывков кода внутри статьи. Например, если пишете инструкцию по созданию формы обратной связи.
После добавления макроса информация стала более заметной и читаемой.
Макросы для интеграции внутреннего контента
- создают «зеркало» статьи или ее отрывка в другом пространстве,
- поддерживают автообновление: достаточно внести правки в оригинал, и все интеграции обновятся сами,
- помогают быстро перейти из «зеркала» в оригинальную статью и углубиться в нужный материал.
Главный профит этого макроса в обновлении: если в исходной статье что-то поменяется, цитата или страница-зеркало изменится вместе с ней. Это намного эффективнее ручного обновления скопипащенного отрывка.
- перейти в режим редактирования на той странице, где содержится необходимая информация,
- выделить предложение, абзац или несколько абзацев, которые надо процитировать,
- вставить макрос «Выборка».
Теперь открываем ту статью, которая будет содержать эту цитату и вставляем макрос «Включить выборку». Вуаля — цитата появилась на странице. Если исходный текст цитаты поменяется, он обновится автоматически во всех статьях, где будет включена эта выборка.
Если нужно процитировать статью целиком, то на помощь придет макрос «Включить страницу». Здесь после выбора макроса нужно ввести название статьи, которую будем транслировать на этой странице. Дополнительно включать выборку на исходной не нужно.
Макросы интеграции внешнего контента
- позволяют размещать контент из внешних источников без дополнительных авторизаций,
- можно вставить задачи из Jira и видеть актуальный статус, не переходя в таск трекер,
- взаимодействие с интерактивным виджетом происходит прямо в Confluence.
Самый простой пример такой внешней интеграции — добавление на страницу задач из Jira.
Таски добавляются через макрос «Фильтр\проблема Jira» — достаточно ввести код проекта и номер задачи. В Confluence подтянется ее название и актуальный статус.
На этой странице собрана часть задач по созданию кластера Managed Kubernetes. Видно название задачи, ее код в таск-трекере, а также статус в реальном времени. По клику по коду задачи можно перейти в Jira и посмотреть подробности.
Еще один полезный макрос интеграции внешнего контента — «Коннектор виджета». С его помощью на страницу можно добавить любой контент из интернета, будь то видео с YouTube, Google-документ или таблица. Все будет отображаться прямо в Confluence без дополнительных авторизаций.
Например, можно собрать галерею из выступлений коллег. На скриншоте — наша подборка докладов сотрудников Selectel.
Где больше узнать про макросы
У Confluence есть много возможностей для работы с контентом. И этот текст, конечно же, не является исчерпывающим руководством.
Если макросов «базовой комплектации» не хватает, то на помощь придет Atlassian Market. В нем можно выбрать из тысячи решений именно то, которое подойдет под потребности вашего проекта. Среди дополнений есть предложения и самого Atlassian, и сторонних разработчиков, которые делали макросы для себя, а после удачного запуска представили их широкой аудитории.
Больше полезной информации по работе с Confluence можно найти в корпоративном университете Atlassian Univercity или на ютуб-канале Atlassian.
Добавить информационную страницу/оглавление раздела
2. Заполните все поля: введите название страницы, содержание страницы*, и Содержимое. Содержимое 1. 4 — это кнопки навигации по лекции, Вы можете создать кнопку для перехода в начало страницы, на следующую/предыдущую страницу, в конец/начало лекции или закончить лекцию. Нажмите Сохранить страницу.
*Содержание страницы Вы можете импортировать из файла формата *.docx, для этого воспользуйтесь инструкцией Импорт текста из Word в Moodle.
Как в confluence сделать оглавление
Проектирование в Confluence
- Вы создаете шаблон для информации определенного типа.
- В этот шаблон добавляете метки и свойства страницы в макросе.
- В любом удобном месте создаете корневую страницу с кнопкой, по клику на которую создается дочерняя страница из шаблона.
- Пускаете на корневую страницу пользователей, которые потенциально будут генерировать нужную информацию (по нужному шаблону, нажимая на кнопку).
- Собираете себе отчет по свойствам страницы через метки, которые вы указали в шаблоне.
- Радуетесь: у вас есть вся нужная информация в удобном формате.
- Если вы решите поменять названия или состав свойств страницы, вам придется проапдейтить все уже созданные объекты, чтобы их данные корректно подтянулись в сводный отчет. Это печально, но, с другой стороны, заставляет детально продумать «архитектуру» вашего набора информации, что является весьма интересной задачей.
- Вам придется написать приличное количество инструкций о том, как заполнять информационные таблицы и пользоваться тегами. Но, с другой стороны, вы можете просто кинуть во всех нужных людей этой статьей.
Организация совместной работы в команде с помощью Confluence
Главные концепции Confluence
- Это онлайн приложение созданное для помощи командам в организации и обсуждении совместной работы
- В Confluence информация агрегируется в пространствах, которые состоят из страниц
- Страницы содержат информацию которую команда генерирует, обсуждает и редактирует по усмотрению
- Пространство — то, над чем работает ваша команда. Информация о текущих проблемах и протоколах собраний, проектных планах и сроках, техническая документация и др. — собирается в пространстве. Это информационный портал для вашей команды. Маленькая команда знает, что ей нужно пространство как для себя, так и для своих проектов.
- Домашняя страница: Она же и первая страница личного пространства, которую видят другие когда “посещают” вас. Содержит краткую биографию о вас и о участии в жизни компании.
- Страницы только для вас: Размещайте черновые планы проектов или макеты. Готовую для «выхода в свет» информацию переносите в пространство команды или проекта.
- Страницы для вашей работы: Создавайте страницы, чтобы следить за достижениями за квартал, или для записи заметок с конференции в которой вы участвовали.
- Главная страница команды: Используйте эту страницу для представления вашей команды, текущих проектов.
- Ярлыки пространства: Используйте ярлыки пространства в боковой панели для ссылок на необходимые страницы, доступ к которым вашей команде нужен постоянно, к примеру дорожная карта проекта или доски JIRA Agile.
- Страницы из шаблонов: Каждый раз когда вы создаёте страницу через шаблон с протоколом собрания, файлами или голосованием, Confluence автоматически добавляет ссылку в боковую панель.
- Если вы создаёте страницу из главного меню в верхней части экрана(синяя кнопка Создать), убедитесь что вы выбрали соответствующее пространство
- Если вы новичок в Confluence, начните с шаблона
- Разрешите членам компании, просматривать и добавлять контент в пространстве, но не разрешайте удалять
- Дайте полный доступ вашей команде (это право удаление и добавление контента)
Table of Contents Macro
Add the Table of Contents macro to a page to help your readers skip directly to the information they’re looking for.
This macro is great for situations where:
you have a large page with lots of information
you want to build your headings into a neat table of contents.
This macro is popular because it helps you navigate lengthy pages. The macro organises your table of contents by nesting Heading 2 under Heading 1, and indenting progressively, like in the image below.
On this page:
Screenshot: Table of Contents macro neatly organises lengthy blog content.
Using the Table of Contents macro
To add the Table of Contents macro to a page:
From the editor toolbar, choose Insert > Other Macros.
You can then publish your page to see the macro in action.
Screenshot: Entering parameters for the Table of Contents macro.
Change the macro parameters
Macro parameters are used to change the behaviour of a macro.
To change the macro parameters:
- In the editor, click the macro placeholder and choose Edit.
- Update the parameters as required then choose Insert.
Here’s a list of the parameters available in this macro.
Output Type
(type )
- list — produces a typical list-type table of contents.
- flat — produces a horizontal menu-type series of links.
Display Section Numbering
(outline )
Select the check box to apply outline numbering to your headings, for example: 1.1, 1.2, 1.3.
List Style
(style )
Select the style of bullet point for each list item. Enter any valid CSS style, such as:
- default — matches Confluence’s default bullet style which uses a different style for each level
- none — no bullet
- disc — a filled circle
- circle — an open circle
- square — a square
- decimal — a numbered list (1, 2, 3, 4, 5)
- lower-alpha — a lower-case, alphabetical list (a, b, c, d, e)
- lower-roman — a lower roman numeral list (i, ii, iii, iv, v, vi)
- upper-roman — an upper roman numeral list (I, II, III, IV, V, VI)
Heading Indent
(indent )
Sets the indent for a list according to CSS quantities. Entering 10px will successively indent heading groups by 10px. For example, level 1 headings will be indented 10px and level 2 headings will be indented an additional 10px.
Separator
(separator )
This parameter applies to flat lists only. You can enter any of the following values:
- brackets — Each item is enclosed by square brackets: [ ].
- braces — Each item is enclosed by braces: .
- parens — Each item is enclosed by parentheses: ( ).
- pipe — Each item is separated by a pipe:
- anything — Each item is separated by the value you enter. You can enter any text as a separator, for example «***». If using a custom separator, be aware that text displays exactly as entered, with no additional white space to further separate the characters.
Minimum Heading Level
(minLevel )
Select the highest heading level to start your TOC list. For example, entering 2 will include levels 2, and lower, headings, but will not include level 1 headings.
Maximum Heading Level
(maxLevel )
Select the lowest heading level to include. For example, entering 2 will include levels 1 and 2, but will not include level 3 headings and below.
Include Headings
(include )
Filter headings to include according to specific criteria. You can use wildcard characters. See Sun’s Regex documentation for examples of constructing regular expression strings.
Exclude Headings
(exclude )
Filter headings to enclude according to specific criteria. You can use wildcard characters. See Sun’s Regex documentation for examples of constructing regular expression strings.
Printable
(printable )
CSS Class Name
(class )
If you have custom TOC styles in your CSS style sheet, use this parameter to output the TOC inside <div> tags with the specified class attribute.
Where the parameter name used in Confluence storage format or wikimarkup is different to the label used in the macro browser, it will be listed below in brackets ( example ).
Examples
The examples below are based on this table of contents:
Filtered Table of Contents
This example filters the headings to include those that contain ‘Favorite’, but excludes headings which end with ‘Things’. The list is styled with Roman numerals.
Parameter | Value |
---|---|
List Style | upper-roman |
Include Headings | |
Exclude Headings |
The resulting table of contents is:
Flat List
This example filters all headings to render a flat list of ‘Unknowns’ enclosed in square brackets (the default list style).
Parameter | Value |
---|---|
Output Type |
flat |
Maximum Heading Level | |
Include Headings |
The resulting table of contents is:
Other ways to add this macro
Add this macro as you type
Add this macro using wiki markup
This is useful when you want to add a macro outside the editor, for example as custom content in the sidebar, header or footer of a space.
Macro name: toc
Macro body: None.
This example shows a list-type table of contents.
This example shows a flat table of contents.
Notes and known issues
- When you use a Table of Contents macro in a template, you will see an error when you preview the template itself. But the Table of Contents macro works on the pages that people create from the template – the table of contents shows up after they have saved the page. (This is probably because the template is not defined as a page, and the Table of Contents macro works for pages only.)
- The Table of Contents macro only displays page or blog post content. You can’t use it to add a table of contents of headings in a comment for example.
- Due to an outstanding issue in the Table of Contents macro (CONF-10619), the macro browser’s Refresh function does not render any parameter modifications. Currently, the rendering of parameter value modifications to the Table of Contents macro occurs only after the page is saved.
Using HTML heading markup with the Table of Contents macro
The Table of Contents macro cannot handle HTML heading markup on its own. Hence, if you use the HTML and HTML Include macros to render HTML heading markup in a Confluence page, the Table of Contents macro will not create a contents list out of these headings.
However, if you insert an HTML anchor into each HTML heading on your page (based on the following syntax), the Table of Contents macro will incorporate these headings into your contents list.
The syntax for the anchor name is the page name and heading name separated by a hyphen. Remove all spaces and convert all text to lower case. Convert all punctuation marks to their URL-encoded equivalent.
Do more with Confluence
Extend Confluence with one of the hundreds of other macros in the Atlassian Marketplace. Here’s some specific to documentation:
Table of Contents Macro
Add the Table of Contents macro to a page to help your readers skip directly to the information they’re looking for.
This macro is great for situations where:
you have a large page with lots of information
you want to build your headings into a neat table of contents.
This macro is popular because it helps you navigate lengthy pages. The macro organises your table of contents by nesting Heading 2 under Heading 1, and indenting progressively, like in the image below.
On this page:
Screenshot: Table of Contents macro neatly organises lengthy blog content.
Using the Table of Contents macro
To add the Table of Contents macro to a page:
From the editor toolbar, choose Insert > Other Macros.
You can then publish your page to see the macro in action.
Screenshot: Entering parameters for the Table of Contents macro.
Change the macro parameters
Macro parameters are used to change the behaviour of a macro.
To change the macro parameters:
- In the editor, click the macro placeholder and choose Edit.
- Update the parameters as required then choose Insert.
Here’s a list of the parameters available in this macro.
Output Type
(type )
- list — produces a typical list-type table of contents.
- flat — produces a horizontal menu-type series of links.
Display Section Numbering
(outline )
Select the check box to apply outline numbering to your headings, for example: 1.1, 1.2, 1.3.
List Style
(style )
Select the style of bullet point for each list item. Enter any valid CSS style, such as:
- default — matches Confluence’s default bullet style which uses a different style for each level
- none — no bullet
- disc — a filled circle
- circle — an open circle
- square — a square
- decimal — a numbered list (1, 2, 3, 4, 5)
- lower-alpha — a lower-case, alphabetical list (a, b, c, d, e)
- lower-roman — a lower roman numeral list (i, ii, iii, iv, v, vi)
- upper-roman — an upper roman numeral list (I, II, III, IV, V, VI)
Heading Indent
(indent )
Sets the indent for a list according to CSS quantities. Entering 10px will successively indent heading groups by 10px. For example, level 1 headings will be indented 10px and level 2 headings will be indented an additional 10px.
Separator
(separator )
This parameter applies to flat lists only. You can enter any of the following values:
- brackets — Each item is enclosed by square brackets: [ ].
- braces — Each item is enclosed by braces: < >.
- parens — Each item is enclosed by parentheses: ( ).
- pipe — Each item is separated by a pipe:
- anything — Each item is separated by the value you enter. You can enter any text as a separator, for example «***». If using a custom separator, be aware that text displays exactly as entered, with no additional white space to further separate the characters.
Minimum Heading Level
(minLevel )
Select the highest heading level to start your TOC list. For example, entering 2 will include levels 2, and lower, headings, but will not include level 1 headings.
Maximum Heading Level
(maxLevel )
Select the lowest heading level to include. For example, entering 2 will include levels 1 and 2, but will not include level 3 headings and below.
Include Headings
(include )
Filter headings to include according to specific criteria. You can use wildcard characters. See Sun’s Regex documentation for examples of constructing regular expression strings.
Exclude Headings
(exclude )
Filter headings to enclude according to specific criteria. You can use wildcard characters. See Sun’s Regex documentation for examples of constructing regular expression strings.
Printable
(printable )
CSS Class Name
(class )
If you have custom TOC styles in your CSS style sheet, use this parameter to output the TOC inside <div> tags with the specified class attribute.
Where the parameter name used in Confluence storage format or wikimarkup is different to the label used in the macro browser, it will be listed below in brackets ( example ).
Examples
The examples below are based on this table of contents:
Filtered Table of Contents
This example filters the headings to include those that contain ‘Favorite’, but excludes headings which end with ‘Things’. The list is styled with Roman numerals.
Parameter | Value |
---|---|
List Style | upper-roman |
Include Headings | |
Exclude Headings |
The resulting table of contents is:
Flat List
This example filters all headings to render a flat list of ‘Unknowns’ enclosed in square brackets (the default list style).
Parameter | Value |
---|---|
Output Type |
flat |
Maximum Heading Level | |
Include Headings |
The resulting table of contents is:
Other ways to add this macro
Add this macro as you type
Add this macro using wiki markup
This is useful when you want to add a macro outside the editor, for example as custom content in the sidebar, header or footer of a space.
Macro name: toc
Macro body: None.
This example shows a list-type table of contents.
This example shows a flat table of contents.
Notes and known issues
- When you use a Table of Contents macro in a template, you will see an error when you preview the template itself. But the Table of Contents macro works on the pages that people create from the template – the table of contents shows up after they have saved the page. (This is probably because the template is not defined as a page, and the Table of Contents macro works for pages only.)
- The Table of Contents macro only displays page or blog post content. You can’t use it to add a table of contents of headings in a comment for example.
- Due to an outstanding issue in the Table of Contents macro (CONF-10619), the macro browser’s Refresh function does not render any parameter modifications. Currently, the rendering of parameter value modifications to the Table of Contents macro occurs only after the page is saved.
Using HTML heading markup with the Table of Contents macro
The Table of Contents macro cannot handle HTML heading markup on its own. Hence, if you use the HTML and HTML Include macros to render HTML heading markup in a Confluence page, the Table of Contents macro will not create a contents list out of these headings.
However, if you insert an HTML anchor into each HTML heading on your page (based on the following syntax), the Table of Contents macro will incorporate these headings into your contents list.
The syntax for the anchor name is the page name and heading name separated by a hyphen. Remove all spaces and convert all text to lower case. Convert all punctuation marks to their URL-encoded equivalent.
Do more with Confluence
Extend Confluence with one of the hundreds of other macros in the Atlassian Marketplace. Here’s some specific to documentation: