作为主题开发者,您经常会遇到一种情况:需要创建仅在社区首页显示的内容。
您可能在主题的“页眉后”部分添加了一些 HTML,这样它会在每个页面上显示。您可以在 CSS 中费一番周折,将其隐藏,只在首页显示……但更好的方法是使用 Discourse 主题创建一个组件,其中的内容仅在您的首页可见。
如果您不熟悉 Discourse 主题,请查看 Beginner's guide to using Discourse Themes 和 https://meta.discourse.org/t/structure-of-themes-and-theme-components/60848。
在您的 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>这是我的首页 HTML 内容</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 上提出。
