# “추천 카테고리” 홈페이지 배너 만들기

**URL:** https://meta.discourse.org/t/creating-a-featured-categories-homepage-banner/143930
**Category:** Development
**Created:** [3월 11, 2020, 4:12오후 UTC](https://meta.discourse.org/t/creating-a-featured-categories-homepage-banner/143930 "2020-03-11T16:12:35Z")
**Posts on this page:** 10
**Page:** 1

<div class="post-metadata">

### Author: ![edL](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/edl/32/139152_2.png) [@edL](https://meta.discourse.org/u/edL)
#### Post date: [3월 11, 2020, 4:12오후 UTC](https://meta.discourse.org/t/creating-a-featured-categories-homepage-banner/143930/1 "2020-03-11T16:12:35Z")

</div>

홈페이지 헤더 아래에 배너 섹션을 만들고, 여기에 좀 더 화려하게 꾸민 카테고리 박스를 배치하고 싶습니다. 예를 들면:

 ![Screenshot 2020-03-11 at 16.02.43](https://global.discourse-cdn.com/meta/original/3X/f/4/f442f81123c392b26949685764f89345eaf5ba55.png)

“below-site-header” 아웃렛과 [홈페이지에서만 표시되는 사용자 지정 콘텐츠 추가 방법](https://meta.discourse.org/t/how-to-add-custom-content-that-only-appears-on-your-homepage/131415) 설명서를 사용하여 마크업을 출력할 수 있다는 점은 알고 있습니다.

이상적으로는, 여기에 어떤 카테고리를 표시할지 선택할 수 있는 사용자 지정 설정 enum 필드를 가지고 싶습니다. 카테고리를 검색할 수 있는 사용자 지정 설정 필드를 만들 수 있을까요?

또한, 카테고리 배경 이미지 외에도 이 카드에 사용자 지정 배경 이미지를 사용하고 싶습니다. 카테고리 설정 모달의 Images 탭에 파일 입력 필드를 하나 더 추가할 수 있을까요? 예를 들면:

 ![Screenshot 2020-03-11 at 16.15.10](https://global.discourse-cdn.com/meta/original/3X/4/f/4f1e0c10ecd09398851d9241b2721daced1fd3f4.png)

전체적으로 이것이 실현 가능한지, 그리고 주의해야 할 잠재적인 함정이나 팁이 있는지 알려주시면 좋겠습니다.

---

<div class="post-metadata">

### Author: ![merefield](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/merefield/32/176214_2.png) [@merefield](https://meta.discourse.org/u/merefield)
#### Post date: [3월 11, 2020, 4:30오후 UTC](https://meta.discourse.org/t/creating-a-featured-categories-homepage-banner/143930/2 "2020-03-11T16:30:52Z")

</div>

시작점으로 [TLP 플러그인](https://meta.discourse.org/t/topic-list-previews/101646?u=merefield)을 사용하는 것을 고려해 보세요. 이미 주제를 가리키는 Featured Images 기능이 있습니다. 일부 코드를 재사용할 수 있을 것입니다.

---

<div class="post-metadata">

### Author: ![anon48433008](https://avatars.discourse-cdn.com/v4/letter/a/22d042/32.png) [@anon48433008](https://meta.discourse.org/u/anon48433008)
#### Post date: [3월 11, 2020, 4:33오후 UTC](https://meta.discourse.org/t/creating-a-featured-categories-homepage-banner/143930/3 "2020-03-11T16:33:03Z")

</div>

그는 이것을 사용할 수 있을까요?

> [@Versatile Banner](https://meta.discourse.org/t/versatile-banner/109133):
>
> discourseSummary Versatile Banner adds a customizable banner to your site.eyeglassesPreview [Preview on Discourse Theme Creator](https://discourse.theme-creator.io/theme/Discourse/versatile-banner)hammer_and_wrenchRepository Link [https://github.com/discourse/discourse-versatile-banner](https://github.com/discourse/discourse-versatile-banner)open_bookNew to Discourse Themes? [Beginner’s guide to using Discourse Themes](https://meta.discourse.org/t/beginners-guide-to-using-discourse-themes/91966) 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 …

---

<div class="post-metadata">

### Author: ![merefield](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/merefield/32/176214_2.png) [@merefield](https://meta.discourse.org/u/merefield)
#### Post date: [3월 11, 2020, 4:39오후 UTC](https://meta.discourse.org/t/creating-a-featured-categories-homepage-banner/143930/4 "2020-03-11T16:39:48Z")

</div>

주어진 카테고리가 덜 동적이라면 더 정적인 접근 방식이 적절할 수 있습니다 👍

데이터 기반이 아닌지 아닌지 결정해야 할 것 같습니다.

---

<div class="post-metadata">

### Author: ![edL](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/edl/32/139152_2.png) [@edL](https://meta.discourse.org/u/edL)
#### Post date: [3월 11, 2020, 5:28오후 UTC](https://meta.discourse.org/t/creating-a-featured-categories-homepage-banner/143930/5 "2020-03-11T17:28:59Z")

</div>

이상적으로는 '카테고리 박스 with Topics’의 고급 버전처럼, 해당 카테고리의 로고와 배경 이미지, 그리고 최신 주제도 함께 가져오는 기능이 있으면 좋겠습니다.

하지만 표준 테마/플러그인 확장 메커니즘을 사용하여 이를 구현하는 것이 쉽지 않다면, 그만한 가치가 없을 수 있습니다. 이 경우 정적으로 처리하거나, 카테고리 박스 홈페이지 레이아웃을 사용하여 필요한 대로 스타일을 적용할 것입니다.

두 가지 핵심 테스트 기준은 다음과 같습니다:

1. ‘카테고리 선택’ 설정 항목을 노출하는 표준적인 방법이 있는가?
2. 카테고리 설정 모달에 메타데이터 필드를 추가하는 표준적인 방법이 있는가?

대안으로, 설정에서 카테고리 ID만 사용할 수 있으면서도 데이터를 프로그래매틱하게 가져올 수 있다면, 그것도 괜찮을 것입니다.

그러나 그런 방식으로 카테고리 데이터에 접근하는 것이 실제로 불가능하다면, 다른 방법 중 하나를 사용할 것입니다.

---

<div class="post-metadata">

### Author: ![merefield](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/merefield/32/176214_2.png) [@merefield](https://meta.discourse.org/u/merefield)
#### Post date: [3월 11, 2020, 5:53오후 UTC](https://meta.discourse.org/t/creating-a-featured-categories-homepage-banner/143930/6 "2020-03-11T17:53:03Z")

</div>

플러그인에서는 \_원하는 것\_을 무엇이든 할 수 있습니다(물론 코어 업데이트 후 플러그인이 깨지는 위험을 최소화하는 전략을 사용하는 것이 가장 좋습니다). 아이디어를 스케치하고, 기존 플러그인 및 디스커스 코어에서 참고한 후, 간단한 버전부터 시작하여 점진적으로 개선해 나가세요.

---

<div class="post-metadata">

### Author: ![jordan.vidrine](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/jordan.vidrine/32/515563_2.png) [@jordan.vidrine](https://meta.discourse.org/u/jordan.vidrine)
#### Post date: [3월 11, 2020, 9:15오후 UTC](https://meta.discourse.org/t/creating-a-featured-categories-homepage-banner/143930/8 "2020-03-11T21:15:16Z")

</div>

Kris님의 이전 게시물을 확인하고, 이를 기반으로 직접 수정하여 여러분이 활용할 수 있는 기초 자료로 만들었습니다. 여기에서 다루는 내용 대부분은 원래 토픽에서 Kris님이 이미 설명해 주셨습니다.  
[https://meta.discourse.org/t/how-to-add-a-featured-topic-list-to-your-discourse-homepage/132949](https://meta.discourse.org/t/how-to-add-a-featured-topic-list-to-your-discourse-homepage/132949)

모든 코드는 테마의 `</head>` `(head_tag.html)` 섹션에 추가됩니다.

첫 번째 섹션은 현재 있는 페이지가 "홈 페이지"인지 확인합니다.

그 다음 `Category.list()` 메서드를 사용하여 사이트의 카테고리를 가져옵니다.

이후 가져온 카테고리들을 특징적으로 표시하고자 하는 카테고리와 비교합니다. 이 비교 대상은 아래 코드에 정의된 `definedFeaturedCategories` 배열에 위치합니다. 허용된 카테고리들은 렌더링을 위해 템플릿으로 전달될 컴포넌트에 설정됩니다.

```xml
<script type="text/discourse-plugin" version="0.8">
  const Category = require("discourse/models/category").default;
  // 사이트 카테고리를 가져오기 위해 Category 모델을 사용할 것입니다

  api.registerConnectorClass('above-main-container', 'featured-categories', {
    // above-main-container는 플러그인 아웃렛이고,
    // featured-topics는 사용자 정의 컴포넌트 이름입니다

    setupComponent(args, component) {

      api.onPageChange((url, title) => {
        console.log(url,title)
        if ((url === "/") || (url === "/latest") ) {
        // 페이지 변경 시 URL이 일치하는지 확인합니다.
        // 홈 페이지가 /latest가 아니라면 /categories로 변경하세요.
        
          $('html').addClass('custom-featured-categories');
          // CSS 타겟팅을 쉽게 하기 위해 HTML 태그에 클래스를 추가합니다.

          let definedFeaturedCategories = ["uncategorized","blog","two"]
          // 특징적으로 표시하고자 하는 카테고리 배열
          // 카테고리 이름을 소문자로 입력하는 것을 확인하세요.

          let featuredCategories = [];

          categories = Category.list();

          for (let cat of categories) {
            if (definedFeaturedCategories.includes(cat.name.toLowerCase())) {
              // 렌더링될 배열에 특징적으로 표시하고자 하는 카테고리만 push합니다.
              featuredCategories.push(cat)
            }
          }

          component.set('featuredCategories', featuredCategories)

        } else {

        // 위의 URL과 페이지가 일치하지 않는 경우 다음을 수행합니다:
          $('html').removeClass('custom-featured-categories');
          // 사용자 정의 클래스를 제거합니다.
          component.set('categories',[])
          // 렌더링을 비활성화하기 위해 카테고리를 빈 배열로 설정합니다.
        }
      });
    }
  });
</script>

```

다음 섹션은 위에서 생성된 컴포넌트의 템플릿을 플러그인 아웃렛 `above-main-container`에 주입합니다. 세 번째 단계에서 생성된 사용자 정의 `categories-wrapper`를 호출하고, `categories`를 위에서 생성된 `featuredCategories`로 정의합니다.

```xml
<script type="text/x-handlebars" data-template-name="/connectors/above-main-container/featured-categories">
      <div class="custom-featured-categories-wrapper">
        {{categories-wrapper categories=featuredCategories}}
          <!-- 아래에서 생성된 categories-wrapper 템플릿을 사용합니다. -->
          <!-- categories를 위에서 스크립트로 생성된 featuredCategories로 정의합니다. -->
      </div>
</script>

```

세 번째 섹션은 특징적인 카테고리를 렌더링하기 위한 사용자 정의 `categories-wrapper` handlebars 템플릿을 생성합니다. 이 부분은 Discourse의 `categories-only.hbs` [Discourse의 카테고리 페이지에서 사용됨](http://app/assets/javascripts/discourse/templates/components/categories-only.hbs)에서 직접 수정되었습니다.

```xml
<script type="text/x-handlebars" data-template-name="components/categories-wrapper">
  <!-- 'categories wrapper'라는 이름의 컴포넌트 템플릿을 생성합니다. -->
  <!-- 이 템플릿 코드의 모든 부분은 Discourse 자체의 카테고리 페이지 템플릿에서 수정되었습니다.
   https://github.com/discourse/discourse/blob/acd1693dac1bff6ff50250d942134bc48a27ff14/app/assets/javascripts/discourse/templates/components/categories-only.hbs -->

  <div class="top-categories-wrapper">
    {{#each categories as |c|}}
        <div class="top-category-column-one">
          {{category-title-link category=c}}
          {{#if c.escription}}
            <div class="category-description">
              {{dir-span c.description}}
            </div>
          {{/if}}
          {{#if c.isGrandParent}}
            <table class="category-list subcategories-with-subcategories">
              <tbody>
                {{#each c.subcategories as |subcategory|}}
                  <tr
                    data-category-id={{subcategory.id}}
                    data-notification-level={{subcategory.notificationLevelString
                    }}
                    class="{{if
                        subcategory.description_excerpt
                        "has-description"
                        "no-description"
                      }}
  
                      {{if subcategory.uploaded_logo.url "has-logo" "no-logo"}}"
                  >
                    <td
                      class="category"
                      style={{border-color subcategory.color}}
                    >
                      {{category-title-link tagName="h4" category=subcategory}}
                      {{#if subcategory.description_excerpt}}
                        <div
                          class="category-description subcategory-description"
                        >
                          {{{dir-span subcategory.description_excerpt}}}
                        </div>
                      {{/if}}
                      {{#if subcategory.subcategories}}
                        <div class="subcategories">
                          {{#each subcategory.subcategories as |subsubcategory|
                          }}
                            {{#unless subsubcategory.isMuted}}
                              <span class="subcategory">
                                {{category-title-before category=subsubcategory
                                }}
                                {{category-link subsubcategory hideParent="true"
                                }}
                              </span>
                            {{/unless}}
                          {{/each}}
                        </div>
                      {{else if subcategory.description_excerpt}}
                        <div
                          class="category-description subcategory-description"
                        >
                          {{{dir-span subcategory.description_excerpt}}}
                        </div>
                      {{/if}}
                    </td>
                  </tr>
                {{/each}}
              </tbody>
            </table>
          {{else if c.subcategories}}
            <div class="subcategories">
              {{#each c.subcategories as |subcategory|}}
                {{#unless subcategory.isMuted}}
                  <span class="subcategory">
                    {{category-title-before category=subcategory}}
                    {{category-link subcategory hideParent="true"}}
                    {{category-unread category=subcategory}}
                  </span>
                {{/unless}}
              {{/each}}
            </div>
          {{/if}}
        </div>
        <div class="top-category-column-two">
          <span class="topics-header">
            Topics
          </span>
          <span class="topics-count">
            {{c.topic_count}}
          </span>
          {{category-unread category=c tagName="div" class="unread-new"}}
        </div>
    {{/each}}
  </div>
</script>

```

이것은 OP에서 요청하신 작업을 시작하는 데 도움이 될 것입니다.

세 번째 섹션에서 각 카테고리 박스의 색상을 사용자 정의된 색상으로 스타일링하려면, `# + c.color`를 사용하여 카테고리의 색상 코드에 접근하여 스타일을 하드코딩할 수 있습니다.

그 외의 스타일링은 `common.scss` 파일에서 수행할 수 있습니다.

---

<div class="post-metadata">

### Author: ![edL](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/edl/32/139152_2.png) [@edL](https://meta.discourse.org/u/edL)
#### Post date: [3월 12, 2020, 10:14오전 UTC](https://meta.discourse.org/t/creating-a-featured-categories-homepage-banner/143930/9 "2020-03-12T10:14:15Z")

</div>

와! @jordan.vidrine님, 이렇게 상세하고 정말 도움이 되는 답변을 주셔서 감사합니다! 한번 시도해 보고 어떻게 되는지 알려드릴게요 🙂

---

<div class="post-metadata">

### Author: ![edL](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/edl/32/139152_2.png) [@edL](https://meta.discourse.org/u/edL)
#### Post date: [3월 12, 2020, 5:02오후 UTC](https://meta.discourse.org/t/creating-a-featured-categories-homepage-banner/143930/10 "2020-03-12T17:02:50Z")

</div>

잘 작동했습니다, @jordan.vidrine:

 ![Screenshot 2020-03-12 at 16.58.46](https://global.discourse-cdn.com/meta/original/3X/1/4/14023c633eb0a19e907aebd31f247814c829d2fa.jpeg)

유일하게 이상한 점은 /categories를 방문한 후에만 주제들이 로드된다는 것입니다. 그렇지 않으면 아예 주제가 없는 것처럼 보입니다:

 ![Screenshot 2020-03-12 at 16.59.57](https://global.discourse-cdn.com/meta/original/3X/8/8/88b805066abd7c1999d377c5abccdbdd5b4263be.jpeg)

여기서 무슨 일이 일어나고 있는지 혹시 아는 분 계신가요?

---

<div class="post-metadata">

### Author: ![jordan.vidrine](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/jordan.vidrine/32/515563_2.png) [@jordan.vidrine](https://meta.discourse.org/u/jordan.vidrine)
#### Post date: [3월 12, 2020, 7:37오후 UTC](https://meta.discourse.org/t/creating-a-featured-categories-homepage-banner/143930/11 "2020-03-12T19:37:34Z")

</div>

음. 죄송하지만 잘 모르겠어요. 해당 문제를 재현할 수 없어요.
