0

I'm having the following problem when trying to render some object's variables on handlebars:

I've declared a static object

public static class Banana
{
    public static String name = "PAPI PAPI";
    public static int id= 9;

    public Banana( )
    {

    }

    @Override
    public String toString() {
        return "Banana{" +
                       "id=" + id +
                       ", name='" + name + '\'' +
                       '}';
    }
}

the next step is trying to render on handlebars my object variables. With that purpose I've done the following:

static void test(RoutingContext ctx)
{
    HttpServerRequest req = ctx.request();
    HttpServerResponse resp = ctx.response();
    resp.setChunked(true);

    resp.putHeader("content-type", "text/html");

    ctx.put("banana", new Banana());
    engine.render(ctx, "src/main/java/templates","/banana.hbs",
         res -> {
             if (res.succeeded()) {
                 ctx.response().end(res.result());
             } else {
                 ctx.fail(res.cause());
             }});
}

My template (banana.hbs) is the following:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <h1>{{banana.id}}</h1>
    <h1>{{banana.name}}</h1>
</body>

The problem is that my Html comes empty:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <h1></h1>
    <h1></h1>
</body>

Can anybody help? Thanks in advance,

1 Answers1

0

I think your problem is the fact that you try put a non-static instance of Banana in your context and there's no property id and name accessible via getters/setters.

I think you could try to change your class definition like that :

public class Banana {
  private String name;
  private Integer id;

  public Banana(Integer id, String name) {
      this.name = name;
      this.id = id;
  }

  // ... toString, Getters and setters ...

  static class Default() {
      private static final Banana instance = new Banana(9, "PAPI PAPI");

      public static Banana getInstance() {
          return instance;
      }
  }
}

And then :

ctx.put("banana", Banana.Default.getInstance());
Idriss Neumann
  • 3,760
  • 2
  • 23
  • 32