Load template in Android app

40 views
Skip to first unread message

Johan Nordberg

unread,
Nov 26, 2016, 8:11:50 AM11/26/16
to mustache.java
I'm having trouble loading templates in my Android app. Right now I have added the template files in the res/raw folder. They cannot be found, so I have loaded the resource as a stream and complied the template using the stream. This works, but it can't find any partial templates. I tried compiling the used templates in the same factory, but that did not work either.

Where in the project structure am I supposed to store the templates?
Do I need to do anything special to load partial templates?

Here's an example of how I load templates now, which work for the base template, but not for partials.

Mustache getMessageTemplate() {
MustacheFactory factory = new DefaultMustacheFactory();
Mustache post = factory.compile(new InputStreamReader(getResources().openRawResource(R.raw.post)), "post");

factory.compile(new InputStreamReader(getResources().openRawResource(R.raw.message)), "message");
factory.compile(new InputStreamReader(getResources().openRawResource(R.raw.alarm)), "alarm");
factory.compile(new InputStreamReader(getResources().openRawResource(R.raw.groupapplicant)), "groupapplicant");
factory.compile(new InputStreamReader(getResources().openRawResource(R.raw.comment)), "comment");

return post;
}


Johan Nordberg

unread,
Nov 26, 2016, 10:38:07 AM11/26/16
to mustache.java
I ended up with creating a custom resolver, like this:

public class RawResourceMustacheResolver implements MustacheResolver {
private Context context;
private String packageName;

public RawResourceMustacheResolver(Context context, String packageName) {
this.context = context;
this.packageName = packageName;
}

@Override
public Reader getReader(String resourceName) {
int resourceId = context.getResources().getIdentifier(resourceName, "raw", packageName);

return new InputStreamReader(context.getResources().openRawResource(resourceId));
}
}

 

Sam

unread,
Nov 28, 2016, 1:48:18 PM11/28/16
to mustache.java
Interesting. I assume that this is Android specific? Maybe I can make an Android module with this.
Reply all
Reply to author
Forward
0 new messages