Only compile a lazily loaded template once. Also fixed styles.

This commit is contained in:
Michael Bayne
2012-04-09 11:15:56 -07:00
parent 37fbeb2bbd
commit 75da7d3e76
@@ -522,28 +522,31 @@ public class Mustache
} }
protected static class IncludedTemplateSegment extends Template.Segment { protected static class IncludedTemplateSegment extends Template.Segment {
public IncludedTemplateSegment (final String templateName, final Compiler compiler) { public IncludedTemplateSegment (String name, Compiler compiler) {
this.compiler = compiler; _name = name;
this.templateName = templateName; _compiler = compiler;
} }
@Override public void execute (Template tmpl, Template.Context ctx, Writer out) { @Override public void execute (Template tmpl, Template.Context ctx, Writer out) {
Reader r; // we compile our template lazily to avoid infinie recursion if a template includes
try { // itself (see issue #13)
r = compiler.loader.getTemplate(templateName); if (_template == null) {
} catch (Exception e) { try {
if (e instanceof RuntimeException) { _template = _compiler.compile(_compiler.loader.getTemplate(_name));
throw (RuntimeException)e; } catch (Exception e) {
} else { if (e instanceof RuntimeException) {
throw new MustacheException("Unable to load template: " + templateName, e); throw (RuntimeException)e;
} else {
throw new MustacheException("Unable to load template: " + _name, e);
}
} }
} }
Template _template = compiler.compile(r);
// we must take care to preserve our context rather than creating a new one, which // we must take care to preserve our context rather than creating a new one, which
// would happen if we just called execute() with ctx.data // would happen if we just called execute() with ctx.data
_template.executeSegs(ctx, out); _template.executeSegs(ctx, out);
} }
protected String templateName; protected final String _name;
protected Compiler compiler; protected final Compiler _compiler;
protected Template _template;
} }
/** A helper class for named segments. */ /** A helper class for named segments. */