使用通用的 BBCode 包装器创建一个主题组件,该组件可以根据字符串变量中的组隐藏内容
显示草稿
创建通用的 BBCode 包装器和主题组件
了解要求
根据您的要求,我们将创建:
一个通用的 BBCode 包装器,可以接受自定义属性。
一个主题组件,该组件根据传递给 BBCode 包装器的组字符串变量隐藏内容。
实现 BBCode 包装器
我们将创建一个可以接受任意属性的 BBCode 包装器。这些属性将传递给主题组件进行评估。
Ruby
# config/initializers/bbcode.rb
Discourse::Plugins::BBCode.add_parser(:hide_if_not_in_group) do |tag, content|
attributes = tag.attributes || {}
"<div class='hide-if-not-in-group' data-group-names='#{attributes[:groups]}'>#{content}</div>"
end
谨慎使用代码。
创建主题组件
主题组件将检查当前用户是否属于 data-group-names 属性中指定的任何组。如果不是,它将隐藏内容。
JavaScript
// app/assets/javascripts/discourse/components/hide-if-not-in-group.js
import Component from 'discourse/components/component';
export default Component.extend({
tagName: 'div',
classNames: ['hide-if-not-in-group'],
didInsertElement() {
const currentUserId = Discourse.currentUser.id;
const groupNames = this.element.dataset.groupNames.split(',');
// Function to check if user is in any of the specified groups
const userIsInAnyGroup = (userId, groupNames) => {
// Replace this with your logic to check user group membership
// For example, using Discourse's API or custom logic
return groupNames.some(groupName => {
// Check if user is in the group named `groupName`
// Return true if the user is in the group, otherwise false
});
};
if (!userIsInAnyGroup(currentUserId, groupNames)) {
this.element.style.display = 'none';
}
}
});
谨慎使用代码。
使用 BBCode
您可以像这样使用 BBCode:
[hide_if_not_in_group groups="staff,moderators"]
This content is hidden for users who are not staff or moderators.
[/hide_if_not_in_group]
重要注意事项
组别成员资格检查:将检查用户组别成员资格的占位符逻辑替换为您实际的实现。您可能需要使用 Discourse 的 API 或自定义逻辑来确定组别成员资格。
性能:对于大量用户或组别,可能需要优化组别成员资格检查。
安全性:确保组别名称得到适当的验证和清理,以防止安全漏洞。
灵活性:考虑允许 BBCode 使用其他属性来控制其他行为(例如,显示消息而不是隐藏内容)。
遵循这些步骤,您将拥有一个灵活的 BBCode 包装器和主题组件,可以根据组别成员资格隐藏内容。
使用 Gemini。我能够获得上述代码片段。但是,在让它们正常工作方面遇到了一些麻烦。
如果有人能指导我在自定义组件中放置的位置以及需要输入的节和代码修复。
当我将 JavaScript 放入 common 时出现的第一个错误是“import”出现错误,它期望一个 {

