Versatile Banner

:discourse2: Summary Versatile Banner adds a customizable banner to your site.
:eyeglasses: Preview Preview on Discourse Theme Creator
:hammer_and_wrench: Repository Link https://github.com/discourse/discourse-versatile-banner
:open_book: New to Discourse Themes? Beginner’s guide to using Discourse Themes

Install this theme component

Features

This theme component is an evolution of previous banner efforts. The goal is to provide more ease and flexibility through the use of theme settings.

Below is a highlight of the features:

  • Limit display to logged-in users or anonymous users
  • Limit display to be exclusively mobile or desktop
  • Limit display to specific pages
  • Dismissible, expandable, and always visible options
  • Full browser width option
  • Color management
  • Heading and column customization using HTML (see below for more)
  • Persistent state option (see below for more)

Customizing your banner’s content

Banner content is broken up into the main heading and columns. You can have up to 5 columns on your banner, however, the recommended number is 3 or fewer due to width limitations. HTML templates are provided and can be customized to meet your individual needs. You can also control each column’s width and add whatever image or font awesome icon you want to the top of each column.

Using the persistent state option

The persistent state option will rely on up to two cookies. These cookies will contain a name for the banner and a true/false value that relates to the banner’s state. If you have any concerns with using cookies on your site, it’s best to avoid using this setting. Choosing a relative time option for the cookie_lifespan setting will make sure the banner remains closed/expanded/collapsed for that amount of time after the user presses the appropriate button. Without this setting, the banner resets with every full page load. If you make a change to the banner and want to ensure that all users see those changes, even those that had previously closed the banner, be sure to change the “cookie name.” It will essentially reset any persistent state, then allow user to close the banner once more

Settings

Name Description
show for members Display the banner for users logged into the forum
show for anon Display the banner for anonymous users
display on mobile Display the banner on mobile devices
display on desktop Display the banner on desktop computers
display on homepage Display the banner on the homepage
url must contain Enter paths that should display the banner. Add * to the end of the path as a wildcard
dismissible Allow the banner to be closed by users
collapsible Allow the banner to be expanded and collapsed by users
default collapsed state Default collapsed state when collapsible setting is enabled
cookie lifespan The lifespan of the cookie used to remember if the banner has been closed, expanded, or collapsed. If set to “none”, NO cookies will be used with this component, and any previously created cookies related to the banner will be deleted the next time a user performs a full page load. The values are measured as a single unit, so setting “year” will be one year, “week” will be one week, etc.
cookie name When important changes are made to the banner, you must change the cookie name to ensure all your users see the changes.
full width banner Display the banner at full browser width
swap default positioning If there is another banner-related component active, use this to swap its position with the Versatile Banner
plugin outlet below-site-header puts it above the sidebar, above-main-container puts it above the content to the side of the sidebar
banner background image The source url for your background image. Tip: You can upload an image to your main theme and use the url from that, but make sure that you do not use “Uploads” section of this component. Any uploads added to this component will be deleted whenever it is updated.
banner background image dark The source url for your background image when system dark mode is detected.
background color Used in place of a background image
background color dark Used in place of a background image when system dark mode is detected.
primary text color The main text color of the banner
primary text color dark The main text color of the banner when system dark mode is detected
secondary text color The text color of the icon and text headings, and the button background color.
secondary text color dark The text color of the icon and text headings, and the button background color when system dark mode is detected.
link text color The text color of links within the banner
link text color dark The text color of links within the banner when system dark mode is detected.
Translation Default
close.title Close the banner
close.label Close
toggle.title Expand/Collapse the banner
toggle.collapse_label Collapse
toggle.expand_label Expand

:discourse2: Hosted by us? Theme components are available to use on our Pro, Business and Enterprise plans.

Last edited by @derek 2025-09-02T18:39:59Z

Check documentPerform check on document:
101 лайк
Homepage Banner
Homepage specific design and content
Showing two banners: one to anonymous users, and one for logged-in members
Discourse Theme Creation
Activated child Component and broke Discourse!
How to add a simple Banner
Landing page customization
Adding a new banner just above the logo
Banner on Discourse
Ideas for highlighting content on our forum
Impact of component positioning with 2.5.0.beta6
Using an Image for a Global Banner Topic - Dimensions?
Showing a Warning to Non-Registered Users
Homepage Feature
Customise home login page
Enhancing My engineering Community Landing Page - Technology Support Category
How to add top welcome message to the board
How is the Banner at meta.discourse.org created?
Is it possible to change the order of topics?
Can the new About page be more visible?
Need help to emulate old forum
Creating a banner that only 1 group can see, while the other groups don't
Sticky global notice
Banner text customization for Subscriptions plugin
How to I stop topics automatically un-pinning when a user reaches the bottom?
How to insert Versatile Banner before the content of the post.?
Need guidance for adding description bar
Customizing your site with existing theme components
How to Set a Closable Banner at the Top of site?
Order of two items in the same plugin outlet
How to add this type of banner?
Customize Your Site Branding
Can the new About page be more visible?
Asking for advice on "How to create a Banner on the main page"/
No HTML in global notice
Welcome Link Banner theme-component with photos
How to apply CSS code only in the discourse home page?
How to add a header image and customize it
Make the Welcome Banner less intrusive
Your own banner with a link
I want add photo for download my app
How to add title and buttons naturally above forum topics?
Where shall I put this code for a top banner?
Is it possible to insert a box of text between the header and topic list?
How do I create a welcome banner like the one on this site?
Customizing the groups page
What are good plugins or theme components for a forum emphasizing pictures?
Creating a banner to display at the top of your site
Horizon Theme
Missing margin in the .banner- box for Versatile Banner TC
What Are Some Good Welcome Banner Designs?
App interviewer
How minimal is your forum?
How to make the automatic dark theme the same as the selected dark theme?
Hover preview and quote of the day
Creating a "Featured Categories" homepage banner
Making my discourse site look a certain way
Help with alignment in the "versatile banner" plugin
Make Banner Undismissable
Can I add a banner only on my homepage?
Welcome message at the top
Globally pinned topic only appears in one category
Pin a post even in the categories home page
How do i turn of unpin/pin option for my forum users?
[PAID] Assistance to Set-up My Forum
Custom HTML on Groups page
Banner diference mobile/web
Help me code menu top same image
Publish a notification at top of the page
How to create a welcome banner/section?
Landing page customization
Message to display to only users without accounts/logged in?
Turned my Discourse into a successful ecommerce platform!
Category Banners
Adding a new banner just above the logo

Всем привет! Я хочу выровнять весь текст по левому краю, но CSS-тема у меня не работает. Подскажите, пожалуйста, как именно это сделать?

3 лайка

Это то, что вы искали?

Если да, вот быстрый и простой CSS, который, надеюсь, поможет вам начать:

.banner-box {
  h1,
  h2,
  h3,
  .row .single-box {
    text-align: left;
    & .banner-list {
      display: block;
      ul {
        margin: 0 0 9px 25px;
      }
    }
  }

  .section-header {
    .x-title {
      padding: 25px 15px;
    }
    .description p {
      text-align: left;
    }
  }
}

Вам нужно создать новый компонент под названием «Versatile Banner Customizations» и добавить вышеуказанный CSS в раздел Common. Обязательно добавьте новый компонент во все активные темы, использующие Versatile Banner, чтобы применить эту настройку.

5 лайков

У меня это сработало. Большое спасибо.

3 лайка

Здравствуйте,

Возможно ли сделать фоновое изображение кликабельным?

Спасибо за ваш ответ.

Можете привести пример?
Зачем вам это нужно?
Я имею в виду… всё фоновое изображение станет ссылкой?
Если пользователь кликнет в любом месте баннера, его перенаправит по этой ссылке.
Не представляю, зачем это может понадобиться.

1 лайк

Как я могу изменить высоту баннера?

1 лайк

Привет @tshenry, я использую компонент темы Versatile Banner, но он исчезает, когда я снимаю галочку «Отображать на компьютере». На самом деле я хочу показывать баннер только на мобильных устройствах.

Однако, когда я снимаю галочку «Отображать на компьютере»… исчезают оба баннера Versatile Banner — и на компьютере, и на мобильном.
Вот ссылка на сайт, если хотите проверить: https://hec.fm

Не упустил ли я что-то?

1 лайк

Возможно ли отображать ссылки горизонтально и на мобильных устройствах? Я был немного удивлен, увидев, что они появляются друг под другом, а не горизонтально.

1 лайк

Спасибо за сообщение! Извините за задержку с ответом. Я смог воспроизвести описанную вами проблему. Я почти уверен, что понимаю, в чём дело. Я займусь этим в конце этой недели и вернусь к вам с ответом.

Высота баннера в первую очередь зависит от его содержимого, но при необходимости вы можете настроить всё с помощью собственного CSS. Я не уверен, насколько удачно вам удастся разместить три колонки горизонтально на мобильном устройстве, но вы определённо можете попробовать это сделать с помощью пользовательского CSS! Ознакомьтесь с рекомендациями по адресу Making custom CSS changes on your site.

4 лайка

Кажется, у меня возник баг на сайте, связанный с временем жизни куки при сохранении состояния развёрнутого/свёрнутого элемента. Я хочу, чтобы мой сайт запоминал, когда пользователи сворачивают или разворачивают баннер, и сохранял это состояние независимо от действий. На главной странице или при переходе по темам всё работает как ожидалось. Однако, как только я захожу в панель администратора, настройки пользователя, FAQ, раздел «О нас», условия использования, политику конфиденциальности или документацию, а затем возвращаюсь на главную, начинаются странные вещи: иногда баннер оказывается в противоположном состоянии, а иногда даже иконка стрелки, указывающая на сворачивание или разворачивание, отображается неверно.

Вот, иконка стрелки направлена вверх:

Но после перехода в раздел документации и возвращения на главную иконка стрелки оказывается в противоположном направлении.

Это выглядит довольно странно…

2 лайка

Только что обнаружил, что универсальный баннер больше не отображается на странице входа в наш форум (это закрытый форум), как это было раньше.

В настройках компонента отмечена опция «Показывать баннер для анонимных пользователей».

При просмотре HTML-кода вижу div с классом ‘banner-box’ внутри вложенных div с классами ‘emberX’, но внутри div с классом ‘banner-box’ ничего нет — в отличие от HTML-кода для авторизованных пользователей.

Есть какие-то идеи, что может быть не так?

1 лайк

Я только что выкатил небольшое обновление для компонента.

Это должно быть исправлено с помощью обновления выше. Мне очень жаль, что так долго пришлось ждать исправления. Ещё раз спасибо за ваш отчёт!

Вам нужно добавить /login в настройку темы «URL должен содержать». Подробнее см. этот пост.

Об этом уже сообщали один или два раза ранее. К сожалению, мне так и не удалось воспроизвести эту проблему. Я попробую снова, когда будет возможность, используя ваши точные шаги, и посмотрю, получится ли у меня что-то.

3 лайка

Я использую Versatile Banner и пытаюсь превратить его в гигантскую ссылку, которая перенаправляет на другой сайт. Как это сделать?

Пытался изменить это через скрипт: api.changeWidgetSetting('banner-content-widget', 'href', '<site_address>'), но Versatile Banner перестал работать.

1 лайк

Спасибо, это отлично! Теперь всё работает идеально! :folded_hands:t2:

2 лайка

Вы, возможно, сможете сделать что-то вроде:

<script type="text/discourse-plugin" version="0.10.0">
  // Добавить ссылку на заголовок
  api.reopenWidget("banner-box-widget", {
    html(attrs) {
      let bannerBox = this._super();
      bannerBox[0].children[1].tagName = "A";
      bannerBox[0].children[1].properties.href = "https://meta.discourse.org";
      return bannerBox;
    }
  });
  
  // Добавить ссылку на остальной контент
  api.reopenWidget("banner-content-widget", {
    html(attrs) {
      let bannerContent = this._super();
      bannerContent.tagName = "A";
      bannerContent.properties.href = "https://meta.discourse.org";
      return bannerContent;
    }
  });
</script>

И добавить правило CSS для настройки цвета ссылки:

.banner-box a {
    color: var(--primary);
}

Если вам не нужна какая-то конкретная функциональность, которую предлагает Versatile Banner, возможно, вам будет проще создать свой собственный простой HTML-баннер в новом компоненте. Примерный вариант:

Добавьте следующее в раздел Common “After Header”:

<a href="https://meta.discourse.org">
  <div class="custom-banner">
    <h2>Это пользовательский баннер!</h2>
  </div>
</a>

А следующее — в раздел Common “CSS”:

 .custom-banner {
   display: flex;
   justify-content: center;
   align-items: center;
   width: $large-width; // 1110px
   height: 200px;
   margin-bottom: 15px;
   background: grey;
   color: white;
 }

Это создаст простой баннер, который полностью кликабелен:

3 лайка

Я устанавливаю этот компонент из git, но, похоже, не получил последний код. Коммит FIX: Work with new sticky header and move away from deprecated $.cookie · discourse/discourse-versatile-banner@0939120 · GitHub не обновился на моём сайте https://ygobbs.com/.

1 лайк

Это связано с тем, что вы используете версию Discourse 2.6.0.beta2. Указанный вами коммит требует версии 2.6.0.beta3 и выше. Обратите внимание, что в этом коммите добавлен файл discourse-compatibility, чтобы предотвратить обновление до коммита, несовместимого с вашей версией Discourse.

5 лайков

Вау, это потрясающе, что Discourse находит для меня более старую версию, вместо того чтобы запрещать установку компонента. Спасибо!

3 лайка

Привет, @tshenry
Я хочу установить компонент несколько раз, чтобы использовать каждый экземпляр для отображения разных баннеров в разных категориях. Поэтому я отключил опцию «Показывать на главной странице» и использовал условие «URL должен содержать», но это мешает работе основного экземпляра, который я использую для отображения компонента только на главной странице. Можете ли вы предложить другое решение или это баг? Спасибо! (:

1 лайк