作为主题开发者,您经常会遇到一种常见情况:需要创建仅在社区主页上显示的内容。
您可能会在主题的“页眉后”(After Header)部分添加一些 HTML,这样它就会出现在每个页面上。您可以通过 CSS 费一番周折来隐藏这些内容,使其除了主页外都不显示……但让我们换个思路,使用 Discourse 主题来创建一个组件,其中的内容仅在您的主页上可见。
如果您对 Discourse 主题不熟悉,请查看 Beginner's guide to using Discourse Themes 和 Structure of themes and theme components
在您的 Discourse 主题中,您需要设置以下目录结构:
javascripts/discourse/components/
javascripts/discourse/connectors/
接下来,我们将创建一个 Ember 组件。您可以从他们的文档中了解有关 Ember 组件的更多信息:Ember.js Guides - Guides and Tutorials - Ember Guides
但就目前而言,这将是一个简单的组件,编写为单个 .gjs 文件,其中包含逻辑和模板。
javascripts/discourse/components/custom-homepage-content.gjs
import Component from "@glimmer/component";
import { service } from "@ember/service";
import { defaultHomepage } from "discourse/lib/utilities";
export default class CustomHomepageContent extends Component {
@service router;
get isHomepage() {
const { currentRouteName } = this.router;
return currentRouteName === `discovery.${defaultHomepage()}`;
}
<template>
{{#if this.isHomepage}}
<h1>This is my homepage HTML content</h1>
{{/if}}
</template>
}
这创建了一个 isHomepage getter,它检查路由器服务中的 currentRouteName —— 如果路由名称与您的主页匹配(由站点设置决定),则返回 true。<template>...</template> 内部的模板会检查该 getter,并仅在其为 true 时显示您的内容。您可以在 {{#if}} 块之间添加任何您想要的 HTML。
现在组件已创建,我们需要将其添加到 Discourse 的某个位置。在这一步,您需要决定使用哪个插件出口(plugin outlet)。这些是 Discourse 中我们为开发者提供的代码钩子区域。您可以 在 Github 上搜索 Discourse 中的这些出口,或者使用 (deprecated) Plugin outlet locations theme component 进行浏览。
对于自定义主页,above-main-container 是一个常见的选择,所以让我们使用它。
我们需要在正确的目录中创建连接器文件:
javascripts/discourse/connectors/above-main-container/custom-homepage-connector.gjs
import CustomHomepageContent from "../../components/custom-homepage-content";
<template><CustomHomepageContent /></template>
就这样,只需要一行代码来调用您的组件 ![]()
本文档受版本控制 - 请在 github 上提出修改建议。
