Создание и управление календарями

:bookmark: Это руководство объясняет, как создавать и управлять календарями в Discourse с помощью плагина Calendar (и Event).

:person_raising_hand: Требуемый уровень пользователя: Все пользователи

Календари — это мощная функция в Discourse, позволяющая организовывать и отображать события внутри вашего сообщества. Это руководство проведет вас через процесс создания календарей, добавления событий и их эффективного управления.

Краткое содержание

  • Включение плагина Calendar
  • Создание календаря в теме или категории
  • Добавление событий в календарь
  • Управление опциями и настройками календаря
  • Использование функции праздничного календаря

Включение плагина Calendar

Прежде чем создавать календари, убедитесь, что плагин «Calendar (and Event)» включен в вашем экземпляре Discourse. Для получения дополнительных сведений о включении плагина и связанных с ним настройках обратитесь к документации по плагину Discourse Calendar and Event.

Создание календаря

Календарь темы

Чтобы встроить календарь в тему:

  1. Создайте новую тему или отредактируйте первый пост существующей темы.

  2. Добавьте следующий код на отдельных строках:

    [calendar]
    [/calendar]
    
  3. Опубликуйте или обновите пост.


:information_source: Первый день недели по умолчанию — понедельник, но его можно настроить с помощью настройки сайта «calendar first day of week» (варианты: суббота, воскресенье или понедельник).

Календарь категории

Чтобы создать календарь для всей категории:

  1. Перейдите в /admin/site_settings/category/discourse_calendar?filter=plugin=discourse-calendar.

  2. В настройке «calendar categories» добавьте запись в следующем формате:

    categoryId=123;tzPicker;defaultView=month
    
    • Замените 123 на ID вашей категории (можно найти в URL при просмотре категории).
  3. Добавьте ID категории в настройку «events calendar categories».

  4. При желании установите «discourse post event allowed on groups», чтобы контролировать, какие группы могут добавлять события.

Добавление элементов в календарь

Календарь темы

Чтобы добавить событие в календарь темы:

  1. Ответьте на тему, содержащую календарь.
  2. Откройте меню опций ⊕ на панели инструментов редактора и используйте функцию «Вставить дату / время», чтобы добавить дату или диапазон дат.
  3. Добавьте описание над датой.
  4. Отправьте ответ.

Событие появится в календаре после перезагрузки темы.

Календарь категории

Чтобы добавить событие в календарь категории:

  1. Создайте новую тему в категории.
  2. Откройте меню опций ⊕ на панели инструментов редактора и выберите «Создать событие».
  3. Заполните детали события и опубликуйте.

Событие появится в календаре категории.

Опции календаря

Вы можете настроить свой календарь, используя различные опции:

Опция Пример Описание
Скрыть выходные weekends="false" Скрывает субботу и воскресенье
Скрыть конкретные дни hiddenDays="1,2" Скрывает понедельник и вторник (используйте 0–6 для воскресенья–субботы)
Установить вид по умолчанию defaultView="month" Варианты: month, week, listNextYear
Игнорировать часовые пояса fullDay="true" Рассматривает все события как целодневные

Пример использования:

[calendar weekends="false" hiddenDays="1,2" defaultView="week" fullDay="true"]
[/calendar]

Удаление элементов календаря

Элементы календаря можно удалить следующими способами:

  • Истекшие элементы календаря могут быть автоматически удалены с помощью настройки «delete expired event posts after».
  • Используйте таймеры тем для автоматического удаления ответов.
  • Вручную удаляйте посты по мере необходимости.

Праздничный календарь

Праздничный календарь — это специальная функция для управления отпусками сотрудников сайта:

  1. Создайте тему с календарем в первом посте.
  2. Установите «holiday calendar topic id» равным ID этой темы.
  3. Ответы на эту тему будут считаться временем отпуска для пользователя, который их опубликовал.
  4. Каждый ответ должен содержать временную метку, добавленную через функцию «Вставить дату / время» в меню опций ⊕ редактора, чтобы она отобразилась в календаре.
  5. Записи об отпусках автоматически и случайно раскрашиваются.
  6. Рядом с именами пользователей, находящихся в отпуске, в карточках пользователей и при упоминаниях @ появляется эмодзи (по умолчанию: :date:).
  7. При желании включите «calendar automatic holidays enabled», чтобы добавить праздники, специфичные для локалей пользователей.

Часто задаваемые вопросы

В: Почему некоторые события, кажется, занимают несколько дней?
О: Календарь всегда работает по UTC. Используйте настройки «all day event start time» и «all day event end time», чтобы скорректировать разницу в часовых поясах.

В: Могу ли я контролировать цвета записей в календаре?
О: Для календарей категорий и предстоящих событий вы можете назначать цвета по тегам или категориям с помощью настройки сайта «map events to color». Записи праздничного календаря автоматически и случайно раскрашиваются и не могут быть настроены.

В: Как отобразить прошлые события в виде списка?
О: В настоящее время существует ошибка при использовании defaultView=listNextYear, из-за которой начальное представление оказывается пустым. В качестве обходного пути пользователям необходимо переключиться на месячный вид, вернуться на один месяц назад, а затем вернуться к списку, чтобы увидеть прошлые события.

Дополнительные ресурсы

11 лайков

I have a hard time understanding how to create a calendar so that it displays in a category, and what to do to fill it once it’s there. For topics, it is quite straightforward, but the category case is more obscure. Can someone give an example?

Create a Category Calendar

The difference between a topic calendar and a category calendar is that the former uses add date from a specific topic response, and displays the calendar in the topic itself, while the latter uses create event in any topic of the configured category, and displays the events calendar in the category.

1. Enable the calendar plugin

In /admin/site_settings/category/discourse_calendar?filter=plugin%3Adiscourse-calendarcalendar categories:

You want something like: categoryId=123;postId=4949;tzPicker;defaultView=month

  • categoryId is easy to find: it’s the number in the URL when you click the #category

  • postId can be found like this: go to the category description (the “About category” pinned topic) and append .json to the URL: the postId is at the beginning of the JSON file.

  • Review the discourse-calendar documentation for available options.

  • Add the category (numbered 123 in our example) to events calendar categories

You may want to set discourse post event allowed on groups to include the groups you want to be able to add events.

2. Create an event

You can create a new topic in category 123 and create event (from the gear button).

The event will then appear on the category calendar.

:tada:

2 лайка

Is there any way to display not the upcoming events, but the ones in the past year? We would like to make use of the plugin for our journal section and list all past entries in the first post.

When using this snippet below, the event list is initially empty. Only when going back to monthly view, going one month back and going back to list view, it works

[calendar defaultView=listNextYear fullDay=true]
[/calendar]

See bug in action:
CleanShot 2024-05-07 at 14.08.49 2

6 лайков

I am interested in this function as well.

I wonder if there might also be some data explorer scripts to go along calender searching

3 лайка

When someone in my community posts a calendar event, then an Admin edits said event, why is then the original poster can no longer edit?

This is a huge deal impacting 100s of people

Make clear that for now only the Topic calendar starts at Monday and that the Category calendar starts at Sunday instead.

Would love to have this admin configurable, as now each one shows the calendar differently…

3 лайка

Uh-huh. That makes sense, because I didn’t realize–

For holidays to be visible in the holiday calendar it is worth mentioning that the reply must content a timestamp that you add from the editors menu.
Also as it was previously state the id of the post is found by adding .json to the url of the post. I think this should be added to the documentation here as if categories have their id in the url the topic url id will confuse people as its number may be close but not similar to the real topic id.

Thank you for this guide anyway, there is a lot to cover because there are many features which is cool, great job devs !

Ahh, the AI rewrite has added some ‘event’ terminology in. Ideally, this term would be avoided in the ‘Calendar’ half of the docs so as not to create ambiguity with the addtional ‘Event’ feature of the plugin.

1 лайк

I want to ask that my discourse don’t have calendar and gear button after I enabled the plugin, is there something wrong?

1 лайк

The gear icon was change to a while ago. I think insert date was moved into that more menu (I think it also uses the icon now).

Definitely a very good point. Looks like this documentation needs an update (and there are probably also other topics that still refer to the gear icon).

1 лайк

Thanks for the response,and then I realized another error that related to this. I have this icon, but it’s bigger and at the wrong spot, blocking, as you can see. It’s normal on the phone, but not on the desktop. By the way, no calendar but events in the list. What can I do :pleading_face:

Does safe mode fix the position of the plus icon?

Which calendar button do you expect?

That one is now

I have this insert button, then how can I post a calendar? I tried code [calendar], that’s working, but is date/time including calendar?

For the big button, I tried safe mode, and it’s still that way. Rebuild app is not working, can I hope for the next version update would fix this?:relieved_face: Or there is something I can do, except doing the whole thing all over again :rofl:

:man_zombie:

This setting seems a likely suspect:

image