TextTemplate class acting strange

Sponge info:

[22:12:53 INFO]: SpongeVanilla
    Minecraft: 1.8.9
    SpongeAPI: 4.1.0-SNAPSHOT-def7d57
    SpongeVanilla: 1.8.9-4.1.0-BETA-291

I am trying to use sponge’s TextTemplate class to replace things in my messages, but I think I am missing something. I’ve consulted the api and all the docs I could find, but to no avail.

If I create a text template via the api and print it out to the console (without replacing any args), I see
Welcome to {server} {player}! (I just followed the tutorial in the documentation, minus the color formatting)
And it works just fine. However, if I then copy and paste that exact text into the TextTemplate#of method, such as
TextTemplate.of("Welcome to {server} {player}!");,
then the template stops working, and I am no longer able to replace the args with actual data.

Am I missing a method or using the api wrong?

Thanks in advance!

Just because that’s what toString() outputs doesn’t mean that it will parse things for you. You have to create it via the API, and if you want to use the of() method, you need to use a TextTemplate.Arg to represent an argument rather than just having it in a string.

toString methods normally just show what the object looks like for debugging purposes and doesn’t usually have a nice formatting.

In the case of TextTemplates you will need to apply the variables to the template.

See https://github.com/SpongePowered/SpongeAPI/blob/master/src/main/java/org/spongepowered/api/text/transform/TextTemplateApplier.java

The correct usage for what you’re trying to achieve is the following:

TextTemplate.of("Welcome to ", TextTemplate.arg("server"), " ", TextTemplate.arg("player"), "!");

The of method does not create a template from a format string.

1 Like