1 52 53 package freemarker.core; 54 55 import java.io.*; 56 import java.util.*; 57 import freemarker.template.*; 58 59 60 72 class Interpret extends BuiltIn 73 { 74 89 TemplateModel _getAsTemplateModel(Environment env) 90 throws TemplateException 91 { 92 TemplateModel model = target.getAsTemplateModel(env); 93 Expression sourceExpr = null; 94 String id = "anonymous_interpreted"; 95 if(model instanceof TemplateSequenceModel) 96 { 97 sourceExpr = ((Expression)new DynamicKeyName(target, new NumberLiteral(new Integer (0))).copyLocationFrom(target)); 98 if(((TemplateSequenceModel)model).size() > 1) 99 { 100 id = ((Expression)new DynamicKeyName(target, new NumberLiteral(new Integer (1))).copyLocationFrom(target)).getStringValue(env); 101 } 102 } 103 else if (model instanceof TemplateScalarModel) 104 { 105 sourceExpr = target; 106 } 107 else 108 { 109 throw invalidTypeException(model, target, env, "sequence or string"); 110 } 111 String templateSource = sourceExpr.getStringValue(env); 112 Template parentTemplate = env.getTemplate(); 113 try 114 { 115 Template template = new Template(parentTemplate.getName() + "$" + id, new StringReader(templateSource), parentTemplate.getConfiguration()); 116 template.setLocale(env.getLocale()); 117 return new TemplateProcessorModel(template); 118 } 119 catch(IOException e) 120 { 121 throw new TemplateException("", e, env); 122 } 123 } 124 125 private static class TemplateProcessorModel 126 implements 127 TemplateTransformModel 128 { 129 private final Template template; 130 131 TemplateProcessorModel(Template template) 132 { 133 this.template = template; 134 } 135 136 public Writer getWriter(final Writer out, Map args) throws TemplateModelException, IOException 137 { 138 try 139 { 140 Environment env = Environment.getCurrentEnvironment(); 141 env.include(template); 142 } 143 catch(TemplateModelException e) 144 { 145 throw e; 146 } 147 catch(IOException e) 148 { 149 throw e; 150 } 151 catch(RuntimeException e) 152 { 153 throw e; 154 } 155 catch(Exception e) 156 { 157 throw new TemplateModelException(e); 158 } 159 160 return new Writer(out) 161 { 162 public void close() 163 { 164 } 165 166 public void flush() throws IOException 167 { 168 out.flush(); 169 } 170 171 public void write(char[] cbuf, int off, int len) throws IOException 172 { 173 out.write(cbuf, off, len); 174 } 175 }; 176 } 177 } 178 } 179 | Popular Tags |