selecting a partial template based on the model type

33 views
Skip to first unread message

J

unread,
Jan 15, 2017, 11:29:54 AM1/15/17
to handlebars.java
Hi,

I was wondering, what is the idiomatic way of selecting a partial template based on the model type?

Suppose we have a class hierarchy:

public class Pet {
private String name;
private String owner;
public Pet(String name, String owner) {
this.name = name;
this.owner = owner;
}
public String getName() { return this.name; }
public String getOwner() { return this.owner; }
}

public class Dog extends Pet {
public Dog(String name, String, owner) { super(name, owner); }
}

public class Cat extends Pet {
public Cat(String name, String, owner) { super(name, owner); }
}

, a model:

Pet[] model = {
new Cat("Mittens", "Pat"),
new Dog("Rocky", "Sue")
};

and partials:

Dog.hbs:

{{ name }} is {{ owner }}'s best friend.

Cat.hbs:

{{ name }} is indifferent about {{ owner }}.

Now, how do I write the template for Pet[]?

I guess I could add "isCat", "isDog" properties to the subtypes and include appropriate partials conditionally:

{{#each}}
{{#if isDog}}{{> Dog}}{{/if}}
{{#if isCat}}{{> Cat}}{{/if}}
{{/each}}

but this feels like a hack and doesn't scale at all. Did I miss something in the documentation or is such usecase not supported?

Regards,

Jakub

edgar

unread,
Jan 15, 2017, 2:26:54 PM1/15/17
to handlebars.java
We do support it :)

Add a getType method to Pet.java and then:

{{#each pets}}

  {{> (lookup this.type) }}

{{/each}}

J

unread,
Jan 17, 2017, 4:24:03 AM1/17/17
to handlebars.java
Works great, thank you.
Reply all
Reply to author
Forward
0 new messages