检索和解析占位符
警告
这些文档是为 SpongeAPI 7 编写的,可能已经过时。 如果你觉得你可以帮助更新它们,请提交一个 PR!
获取一个占位符解析器
PlaceholderParsers 存储在 Sponge 的注册表,这意味着它可以通过与其他 CatalogType: 一样的方式获取。
Sponge.getRegistry().getType(PlaceholderParser.class, id);
小技巧
请记住 PlaceholderParser ID 的格式为 pluginid:placeholderid,例如 sponge:name.
通过占位符创建文本
一个 PlaceholderParser 需要 :javadoc:`PlaceholderContext`来生成合适的 :javadoc:`Component`对象。``PlaceholderContexts`` 可以使用由 PlaceholderContext#builder() 方法获得的 PlaceholderContext.Builder 创建。
这个 Builder 允许提供以下可选上下文:
生成的 PlaceholderContext 可以通过 Placeholder Parser#parse(PlaceholderContext) 提供给 PlaceholderParser 。
例如,如果你想通过 sponge:name 解析器包含玩家的名字,你可以这样做:
Player player = ...;
// We know this exists
PlaceholderParser parser = PlaceholderParsers.NAME;
PlaceholderContext context = PlaceholderContext.builder()
    .associatedObject(player)
    .build();
Component text = parser.parse(context);
如果玩家的名字是“SpongePlayer”,返回的文本将是 SpongePlayer
在文本中包含占位符
占位符也可以在 Component 和 ComponentBuilder 对象中使用,无需先解析它们。Sponge 提供了一个 PlaceholderComponent 对象,将一对 PlaceholderParser 和 PlaceholderContext 捆绑在一起 。
要创建一个 PlaceholderComponent ,请使用 PlaceholderComponent#builder() 并酌情添加 PlaceholderParser 和 PlaceholderContext 对象。然后你可以在 Component 对象中使用内置的 PlaceholderComponent 。
如果你想使用前一个示例的 Component 中的解析器和上下文,你可以像下面这样写:
PlaceholderComponent placeholderText = PlaceholderComponent.builder().context(context).parser(parser).build();
Component result = Component.text("Hello! Your name is ")
    .append(placeholderText)
    .append(Component.text("!"));
文本将是“Hello! Your name is SpongePlayer!”
备注
一个 PlaceholderComponent 将会在使用 Component#append(Component) 添加到 Component 或 ComponentBuilder 后立即解析。