首页内容
作为主题开发者,你经常会遇到这样一种情况:需要创建只在社区首页显示的内容。
你可以在主题的"页眉后"部分添加一些 HTML,这些内容随后会出现在每个页面上。你可以在 CSS 上费些周折,把首页以外的这些内容隐藏掉……不过这里我们用 Discourse 主题来创建一个组件,让内容只在你的首页可见。
如果你不熟悉 Discourse 主题,请查看 https://meta.discourse.org/t/beginners-guide-to-using-discourse-themes/91966 和 https://meta.discourse.org/t/structure-of-themes-and-theme-components/60848
在 Discourse 主题中,你需要建立以下目录结构:
:file_folder: javascripts/discourse/components/
:file_folder: javascripts/discourse/connectors/
接下来我们要创建一个 Ember 组件。关于 Ember 组件的更多信息,请参阅其文档:https://guides.emberjs.com/release/
不过这里只是一个简单的组件,写成单个 .gjs 文件,同时包含逻辑和模板。
:page_facing_up: 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,它会检查 router service 中的 currentRouteName。如果路由名称与你的首页(由站点设置决定)匹配,它将返回 true。<template>...</template> 内的模板会检查这个 getter,只有当它为 true 时才显示你的内容。你可以在 {{#if}} 块之间添加任意 HTML。
组件创建完成后,我们需要把它添加到 Discourse 的某个位置。在这一步,你需要决定使用哪个插件出口。这些是 Discourse 各处预留的少量代码位置,供开发者挂接自己的代码。你可以在 Github 上搜索这些插件出口,或使用 https://meta.discourse.org/t/plugin-outlet-locations-theme-component/100673/1/. 来浏览它们。
对于自定义首页,above-main-container 是一个常见的选择,我们就用它。
我们需要在正确的目录中创建连接器文件:
:page_facing_up: javascripts/discourse/connectors/above-main-container/custom-homepage-connector.gjs
import CustomHomepageContent from "../../components/custom-homepage-content";
<template><CustomHomepageContent /></template>
:point_up: 就是这些,只需要一行代码调用你的组件 :tada:

谢谢你的反馈!