
com.hubspot.jinjava.Jinjava Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jinjava Show documentation
Show all versions of jinjava Show documentation
Jinja templating engine implemented in Java
/**********************************************************************
* 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 javax.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:
*
*
* Jinjava jinjava = new Jinjava();
* Map<String, Object> context = new HashMap<>();
* context.put("name", "Jared");
* // ...
* String template = "Hello, {{ name }}";
* String renderedTemplate = jinjava.render(template, context);
*
*
* @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()
);
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 bindings) {
RenderResult result = renderForResult(template, bindings);
List 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 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 bindings,
JinjavaConfig renderConfig
) {
Context context;
JinjavaInterpreter parentInterpreter = JinjavaInterpreter.getCurrent();
if (parentInterpreter != null) {
renderConfig = parentInterpreter.getConfig();
Map 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.setDynamicVariableResolver(globalContext.getDynamicVariableResolver());
return context;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy