Retrieving and Parsing Placeholders
Waarschuwing
These docs were written for SpongeAPI 7 and are likely out of date. If you feel like you can help update them, please submit a PR!
Obtaining a PlaceholderParser
PlaceholderParsers are stored in the Sponge registry, meaning they can be obtained the same way as any other CatalogType:
Sponge.getRegistry().getType(PlaceholderParser.class, id);
Tip
Remember that the PlaceholderParser
ID is of the form pluginid:placeholderid
, for example sponge:name
.
Creating Text from a PlaceholderParser
A PlaceholderParser
requires a PlaceholderContext in order to generate an appropriate Component
object. PlaceholderContexts
can be created by using a PlaceholderContext.Builder obtained from the
PlaceholderContext#builder() method.
The builder allows for the following optional context to be provided:
An associated object, allowing for the placeholder to modify its output (this will usually be a Player or other Audience)
An argument string that a
PlaceholderParser
can parse
A built PlaceholderContext
can then be supplied to the PlaceholderParser
by using
PlaceholderParser#parse(PlaceholderContext).
For example, if you wish to include a player’s name using the sponge:name
parser, you could do the following:
Player player = ...;
// We know this exists
PlaceholderParser parser = PlaceholderParsers.NAME;
PlaceholderContext context = PlaceholderContext.builder()
.associatedObject(player)
.build();
Component text = parser.parse(context);
If the player name is “SpongePlayer”, the returned text will say SpongePlayer
Including Placeholders in Text
Placeholders can also be used in Component
and ComponentBuilder objects without parsing them
first. Sponge provides a PlaceholderComponent object that bundles a PlaceholderParser
and
PlaceholderContext
together.
To create a PlaceholderComponent
, use PlaceholderComponent#builder() and add the PlaceholderParser
and
PlaceholderContext
objects as appropriate. You can then use the built PlaceholderComponent
in the Component
objects.
If you wished to use the parser and context from the previous example in a Component
, you could write the following:
PlaceholderComponent placeholderText = PlaceholderComponent.builder().context(context).parser(parser).build();
Component result = Component.text("Hello! Your name is ")
.append(placeholderText)
.append(Component.text("!"));
The text will say “Hello! Your name is SpongePlayer!”
Notitie
A PlaceholderComponent
will be parsed as soon as it is added to a Component
or ComponentBuilder
using
Component#append(Component).