How to bring in Latest topics when using category boxes

Hi Guys,

Our HR team have decided to go with category boxes instead of a category list as below.

However, they also would like the latest topics to appear at the bottom of the categories as seen in revoluts community page

I am struggling to work out how this can be done, either as an existing setting or with CSS,

any ideas?

Try to work with components

You can use: categories-and-latest-topics

In this mode, there is a connection and categories and recent topics.

<script type='text/x-handlebars' data-template-name='components/categories-and-latest-topics'>

<div class='column categories'>
  {{categories-only categories=categories}}
</div>

<div class='column'>
  {{categories-topic-list topics=topics filter="latest" class="latest-topic-list"}}
</div>

</script>

Next, you override: categories-only

<script type='text/x-handlebars' data-template-name='components/categories-only'>

   The contents of the file...

</script>

Perhaps from this file it is necessary to move the box with the categories, or to do simply to change the css.

Options think very many.

https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/templates/components/categories-boxes.hbs

Useful material

Another option is to simply structure your category directly

https://meta.discourse.org/c/howto

Then just change the css, which is even easier. )

Ideally I would prefer to do it like you have suggested, however, there isnt a way to display categories in a grid layout and have the latest topics below. :frowning_face:

I suggest building a static header customization if your categories do not change much. Then you could have whatever layout you like above the topic list.

I’ve built this or something similar for a few sites at this point. If you put this in the </head> section of your theme it will put all the categories on top of your home page (and /latest assuming that it’s the same as your homepage)

Then all you’ll need is add the CSS to structure this layout however you want. This is a good introduction to using the API and Handlebars templates in general.

<script type="text/discourse-plugin" version="0.8">
  const ajax = require('discourse/lib/ajax').ajax;

  api.registerConnectorClass('below-site-header', 'custom-homepage', {
    setupComponent(args, component) {
      component.set('hostname', window.location.hostname);
      
      api.onPageChange((url, title) => {
        if (url == "/" || url == "/latest"){ 
          $('html').addClass('show-custom-homepage'); // Show homepage
          component.set('displayCustomHomepage', true);
          
            ajax("/site.json").then (function(result){ // Get list of categories
              let categoryName = [];
              result.categories.forEach(function(categories){
                categoryName.push(categories);
            });
            component.set('categoryName', categoryName);
          });  
        }
        else { // Hide homepage
          $('html').removeClass('show-custom-homepage');
          component.set('displayCustomHomepage', false);
        }
      });
    }
  });
</script>


<script type='text/x-handlebars' data-template-name='/connectors/below-site-header/custom-homepage'>
  
  {{#if displayCustomHomepage}}
  
  <div class="custom-homepage-wrapper"> 

    <div class="wrap wrap-category-boxes">
    
      <div class="homepage-category-boxes">
        {{#each categoryName as |c|}}
        <a href="/c/{{c.slug}}" class="box">
          <div class="homepage-category-box">
            {{#if c.uploaded_logo}}
            <div class="category-image-wrapper">  
              <img class="homepage-category-image" src="{{c.uploaded_logo.url}}" />               
            </div>              
            {{/if}}
            <h2>{{#if c.read_restricted}}<i class="fa fa-lock">&nbsp;</i>{{/if}}{{c.name}}</h2>
            <p>{{c.description}}</p>
          </div>
        </a>
        {{/each}}
      </div>
      
    </div>
    
  </div> 
  {{/if}}

</script>

It looks very nice. How I can to add Font Awesome 5 instead of images? Many thanks!

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

Спасибо за этот фрагмент кода! Я работаю над проектом, в котором мне нужно реализовать некоторые функции по этому принципу (не обязательно категории), и я хотел бы включить это напрямую в плагин, который я разрабатываю.

Я знаю, куда поместить шаблон Handlebars, но не могу найти папку или файл, куда следует добавить JavaScript. Не могли бы вы подсказать, как поступить?

Спасибо,
Тимотеп

Мне нравится эта идея! С нетерпением жду возможности протестировать такой компонент темы или плагин.

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

Да, произошла ошибка! Спасибо, что сообщили о ней. Я исправил код в сообщении выше.

Мы включили строгий режим для нашего JavaScript, поэтому categoryName = []; должно быть объявлено. Исправление заключалось в изменении этой строки на let categoryName = [];.

Эта ссылка на GitHub, ведущая, надеюсь, к компоненту, который выполняет эту задачу, возвращает ошибку 404.

Думаю, этот компонент теперь здесь:

https://github.com/discourse/discourse/blob/main/app/assets/javascripts/discourse/app/templates/components/categories-boxes.hbs

Хорошо… Мне нужно разобраться, как заставить hbs работать как что-то, что можно добавить в Discourse. Я полагаю, мне нужно использовать это как файл в компоненте, и мне нужно найти туториал по этому вопросу?
Я видел один туториал с простой темой. Это правильное направление?

Я раньше этого не делал, поэтому не знаю ответа. Учебник по разработке тем — определенно хорошее место для начала.

Если вы поищете на этой странице “Mounting widgets” («Подключение виджетов»), то увидите пример отображения виджета в другой части страницы.

Эта тема howto также может быть полезна в качестве примера:

https://meta.discourse.org/t/how-to-add-a-featured-topic-list-to-your-discourse-homepage/132949

Сообщу, если у меня получится. Тем временем я подключил тему Air и вполне доволен, но мне всё ещё хотелось бы видеть последние сообщения ниже тем категорий.

Раньше, 25 лет назад, я был программистом на msvc++, и мне удалось создать приложение для Flutter, выпущенное в Play Store. Однако открытые API даются мне непросто. Посмотрим, как пойдут дела. Как только смогу, опубликую обновление.

У вас получилось? Я тоже планирую заняться этим и думаю, есть ли способ проще или же нужно углубиться в тему и потратить время.

Используя настройку стиля страницы категории для десктопа «Ящики с подкатегориями», мне удалось создать компонент темы и добавить код под ящиками. Теперь я пытаюсь разобраться, как вывести список последних тем по всему сайту.

<script type="text/x-handlebars" data-template-name="/connectors/category-boxes-after-boxes/mwp">
<div class='column'>
  {{categories-topic-list topics=topics filter="latest" class="latest-topic-list"}}
</div>
</script>

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

Я сдался. Сейчас я в основном использую стандартные решения.