-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathJinjava.java
More file actions
334 lines (301 loc) · 11.5 KB
/
Jinjava.java
File metadata and controls
334 lines (301 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/**********************************************************************
* Copyright (c) 2014 HubSpot Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**********************************************************************/
package com.hubspot.jinjava;
import com.hubspot.jinjava.doc.JinjavaDoc;
import com.hubspot.jinjava.doc.JinjavaDocFactory;
import com.hubspot.jinjava.el.ExtendedSyntaxBuilder;
import com.hubspot.jinjava.el.TruthyTypeConverter;
import com.hubspot.jinjava.el.ext.eager.EagerExtendedSyntaxBuilder;
import com.hubspot.jinjava.interpret.Context;
import com.hubspot.jinjava.interpret.FatalTemplateErrorsException;
import com.hubspot.jinjava.interpret.InterpretException;
import com.hubspot.jinjava.interpret.InvalidArgumentException;
import com.hubspot.jinjava.interpret.InvalidInputException;
import com.hubspot.jinjava.interpret.JinjavaInterpreter;
import com.hubspot.jinjava.interpret.RenderResult;
import com.hubspot.jinjava.interpret.TemplateError;
import com.hubspot.jinjava.interpret.TemplateError.ErrorType;
import com.hubspot.jinjava.interpret.TemplateSyntaxException;
import com.hubspot.jinjava.lib.exptest.ExpTest;
import com.hubspot.jinjava.lib.filter.Filter;
import com.hubspot.jinjava.lib.fn.ELFunctionDefinition;
import com.hubspot.jinjava.lib.tag.Tag;
import com.hubspot.jinjava.loader.ClasspathResourceLocator;
import com.hubspot.jinjava.loader.ResourceLocator;
import de.odysseus.el.ExpressionFactoryImpl;
import de.odysseus.el.misc.TypeConverter;
import de.odysseus.el.tree.TreeBuilder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import jakarta.el.ExpressionFactory;
/**
* The main client API for the Jinjava library, instances of this class can be used to render jinja templates with a given map of context values. Example use:
*
* <pre>
* Jinjava jinjava = new Jinjava();
* Map<String, Object> context = new HashMap<>();
* context.put("name", "Jared");
* // ...
* String template = "Hello, {{ name }}";
* String renderedTemplate = jinjava.render(template, context);
* </pre>
*
* @author jstehler
*/
public class Jinjava {
private ExpressionFactory expressionFactory;
private ExpressionFactory eagerExpressionFactory;
private ResourceLocator resourceLocator;
private Context globalContext;
private JinjavaConfig globalConfig;
/**
* Create a new Jinjava processor instance with the default global config
*/
public Jinjava() {
this(new JinjavaConfig());
}
/**
* Create a new jinjava processor instance with the specified global config
*
* @param globalConfig
* used for all render operations performed by this processor instance
*/
public Jinjava(JinjavaConfig globalConfig) {
this.globalConfig = globalConfig;
this.globalContext = new Context();
Properties expConfig = new Properties();
expConfig.setProperty(
TreeBuilder.class.getName(),
ExtendedSyntaxBuilder.class.getName()
);
Properties eagerExpConfig = new Properties();
eagerExpConfig.setProperty(
TreeBuilder.class.getName(),
EagerExtendedSyntaxBuilder.class.getName()
);
eagerExpConfig.setProperty(ExpressionFactoryImpl.PROP_CACHE_SIZE, "0");
TypeConverter converter = new TruthyTypeConverter();
this.expressionFactory = new ExpressionFactoryImpl(expConfig, converter);
this.eagerExpressionFactory = new ExpressionFactoryImpl(eagerExpConfig, converter);
this.resourceLocator = new ClasspathResourceLocator();
}
/**
* Set the object responsible for locating templates referenced in other templates
*
* @param resourceLocator
* the locator to use for loading all templates
*/
public void setResourceLocator(ResourceLocator resourceLocator) {
this.resourceLocator = resourceLocator;
}
/**
* @return The EL factory used to process expressions in templates by this instance.
*/
public ExpressionFactory getExpressionFactory() {
return expressionFactory;
}
/**
* @return The EL factory used to eagerly process expressions in templates by this instance.
*/
public ExpressionFactory getEagerExpressionFactory() {
return eagerExpressionFactory;
}
/**
* @return The global config used as a base for all render operations performed by this instance.
*/
public JinjavaConfig getGlobalConfig() {
return globalConfig;
}
/**
* The global render context includes such things as the base set of tags, filters, exp tests and functions, used as a base by all render operations performed by this instance
*
* @return the global render context
*/
public Context getGlobalContext() {
return globalContext;
}
public Context getGlobalContextCopy() {
return copyGlobalContext();
}
public ResourceLocator getResourceLocator() {
return resourceLocator;
}
/**
* @return a comprehensive descriptor of all available filters, functions, and tags registered on this jinjava instance.
*/
public JinjavaDoc getJinjavaDoc() {
return new JinjavaDocFactory(this).get();
}
/**
* @return code snippets of all available filters, functions, and tags registered on this jinjava instance.
*/
public String getJinjavaSnippetDoc() {
return new JinjavaDocFactory(this).getCodeEditorTagSnippets();
}
/**
* Render the given template using the given context bindings.
*
* @param template
* jinja source template
* @param bindings
* map of objects to put into scope for this rendering action
* @return the rendered template
* @throws InterpretException
* if any syntax errors were encountered during rendering
*/
public String render(String template, Map<String, ?> bindings) {
RenderResult result = renderForResult(template, bindings);
List<TemplateError> fatalErrors = result
.getErrors()
.stream()
.filter(error -> error.getSeverity() == ErrorType.FATAL)
.collect(Collectors.toList());
if (!fatalErrors.isEmpty()) {
throw new FatalTemplateErrorsException(template, fatalErrors);
}
return result.getOutput();
}
/**
* Render the given template using the given context bindings. This method returns some metadata about the render process, including any errors which may have been encountered such as unknown variables or syntax errors. This method will
* not throw any exceptions; it is up to the caller to inspect the renderResult.errors collection if necessary / desired.
*
* @param template
* jinja source template
* @param bindings
* map of objects to put into scope for this rendering action
* @return result object containing rendered output, render context, and any encountered errors
*/
public RenderResult renderForResult(String template, Map<String, ?> bindings) {
return renderForResult(template, bindings, globalConfig);
}
/**
* Render the given template using the given context bindings. This method returns some metadata about the render process, including any errors which may have been encountered such as unknown variables or syntax errors. This method will
* not throw any exceptions; it is up to the caller to inspect the renderResult.errors collection if necessary / desired.
*
* @param template
* jinja source template
* @param bindings
* map of objects to put into scope for this rendering action
* @param renderConfig
* used to override specific config values for this render operation
* @return result object containing rendered output, render context, and any encountered errors
*/
public RenderResult renderForResult(
String template,
Map<String, ?> bindings,
JinjavaConfig renderConfig
) {
Context context;
JinjavaInterpreter parentInterpreter = JinjavaInterpreter.getCurrent();
if (parentInterpreter != null) {
renderConfig = parentInterpreter.getConfig();
Map<String, Object> bindingsWithParentContext = new HashMap<>(bindings);
if (parentInterpreter.getContext() != null) {
bindingsWithParentContext.putAll(parentInterpreter.getContext());
}
context =
new Context(
copyGlobalContext(),
bindingsWithParentContext,
renderConfig.getDisabled()
);
} else {
context = new Context(copyGlobalContext(), bindings, renderConfig.getDisabled());
}
JinjavaInterpreter interpreter = globalConfig
.getInterpreterFactory()
.newInstance(this, context, renderConfig);
JinjavaInterpreter.pushCurrent(interpreter);
try {
String result = interpreter.render(template);
return new RenderResult(
result,
interpreter.getContext(),
interpreter.getErrorsCopy()
);
} catch (InterpretException e) {
if (e instanceof TemplateSyntaxException) {
return new RenderResult(
TemplateError.fromException((TemplateSyntaxException) e),
interpreter.getContext(),
interpreter.getErrorsCopy()
);
}
return new RenderResult(
TemplateError.fromSyntaxError(e),
interpreter.getContext(),
interpreter.getErrorsCopy()
);
} catch (InvalidArgumentException e) {
return new RenderResult(
TemplateError.fromInvalidArgumentException(e),
interpreter.getContext(),
interpreter.getErrorsCopy()
);
} catch (InvalidInputException e) {
return new RenderResult(
TemplateError.fromInvalidInputException(e),
interpreter.getContext(),
interpreter.getErrorsCopy()
);
} catch (Exception e) {
return new RenderResult(
TemplateError.fromException(e),
interpreter.getContext(),
interpreter.getErrorsCopy()
);
} finally {
globalContext.reset();
JinjavaInterpreter.popCurrent();
}
}
/**
* Creates a new interpreter instance using the global context and global config
*
* @return a new interpreter instance
*/
public JinjavaInterpreter newInterpreter() {
return globalConfig
.getInterpreterFactory()
.newInstance(this, copyGlobalContext(), this.getGlobalConfig());
}
public void registerTag(Tag t) {
globalContext.registerTag(t);
}
public void registerFunction(ELFunctionDefinition f) {
globalContext.registerFunction(f);
}
public void registerFilter(Filter f) {
globalContext.registerFilter(f);
}
public void registerExpTest(ExpTest t) {
globalContext.registerExpTest(t);
}
private Context copyGlobalContext() {
Context context = new Context(null, globalContext);
// copy registered.
globalContext.getAllExpTests().forEach(context::registerExpTest);
globalContext.getAllFilters().forEach(context::registerFilter);
globalContext.getAllFunctions().forEach(context::registerFunction);
globalContext.getAllTags().forEach(context::registerTag);
context.setAutoEscape(globalContext.isAutoEscape());
context.setDynamicVariableResolver(globalContext.getDynamicVariableResolver());
return context;
}
}