Jinjava Documentation

repository·master·Indexed 20 days ago

https://github.com/hubspot/jinjava

A Java-based implementation of Jinja templates. Jinjava allows for rendering templates with context variables, configuring template loading via ResourceLocators, and extending functionality through custom tags, filters, and functions. It includes configurable error handling strategies via the ErrorHandlingStrategy interface to manage fatal and non-fatal errors.

Tokens
1.6K
Snippets
5
Records
6
Agent score
23%

What's inside Jinjava

  1. Configure Template Loading with ResourceLocators

    master

    Jinjava uses ResourceLocator implementations to resolve template paths (e.g., for {% extends %} or {% include %}).

    • Default Behavior: Uses ClasspathResourceLocator, which loads files from the classpath.
    • File System Access: Use FileResourceLocator to load files from the file system. Warning: This carries security risks if user input is used to define paths, as it could allow unauthorized file access (e.g., {% include '/etc/password' %}).
    • Custom Loading: Implement the ResourceLoader interface to hook into your own application's template repository.
    • Multiple Locators: Use CascadingResourceLocator to search through multiple locations sequentially.

    To set a locator:

    JinjavaConfig config = JinjavaConfig.builder().build();
    Jinjava jinjava = new Jinjava(config);
    
    // Set a single custom locator
    jinjava.setResourceLocator(new MyCustomResourceLocator());
    
    // Set multiple locators (cascading)
    jinjava.setResourceLocator(new MyCustomResourceLocator(), new FileResourceLocator());
  2. Install Jinjava via Maven

    master

    To use Jinjava in your Java project, add the following dependency to your pom.xml. Ensure you are using Java 8 or higher, or use the specific Java 7 compatible version if necessary.

    For Java 8+:

    <dependency>
      <groupId>com.hubspot.jinjava</groupId>
      <artifactId>jinjava</artifactId>
      <version>{ LATEST_VERSION }</version>
    </dependency>

    For Java 7:

    <dependency>
      <groupId>com.hubspot.jinjava</groupId>
      <artifactId>jinjava</artifactId>
      <version>2.0.11-java7</version>
    </dependency>
    <dependency>
      <groupId>com.hubspot.jinjava</groupId>
      <artifactId>jinjava</artifactId>
      <version>{ LATEST_VERSION }</version>
    </dependency>
  3. Render a template with Jinjava

    master

    To render a template, instantiate Jinjava, prepare a Map containing your context variables, and call the render method with the template string and the context.

    Example:

    Template (my-template.html):

    <div>Hello, {{ name }}!</div>

    Java implementation:

    Jinjava jinjava = new Jinjava();
    Map<String, Object> context = Maps.newHashMap();
    context.put("name", "Jared");
    
    String template = Resources.toString(Resources.getResource("my-template.html"), Charsets.UTF_8);
    String renderedTemplate = jinjava.render(template, context);

    Result:

    <div>Hello, Jared!</div>
    Jinjava jinjava = new Jinjava();
    Map<String, Object> context = Maps.newHashMap();
    context.put("name", "Jared");
    
    String template = Resources.toString(Resources.getResource("my-template.html"), Charsets.UTF_8);
    
    String renderedTemplate = jinjava.render(template, context);
  4. Register custom tags, filters, and functions

    master

    You can extend Jinjava's capabilities by registering custom logic into the global context.

    • Tags: Implement com.hubspot.jinjava.lib.Tag.
    • Filters: Implement com.hubspot.jinjava.lib.Filter.
    • Functions: Use ELFunctionDefinition to bind a public static method to a template function name.
    • Importable Classes: Register classes that extend Importable.

    Registration Example:

    // Register a custom tag
    jinjava.getGlobalContext().registerTag(new MyCustomTag());
    
    // Register a custom filter
    jinjava.getGlobalContext().registerFilter(new MyAwesomeFilter());
    
    // Register a custom function (binds to myfn:my_func('foo', 42))
    jinjava.getGlobalContext().registerFunction(new ELFunctionDefinition("myfn", "my_func", 
        MyFuncsClass.class, "myFunc", String.class, Integer.class));
    
    // Register classes extending Importable
    jinjava.getGlobalContext().registerClasses(Class<? extends Importable>... classes);
    jinjava.getGlobalContext().registerTag(new MyCustomTag());
    jinjava.getGlobalContext().registerFilter(new MyAwesomeFilter());
    jinjava.getGlobalContext().registerFunction(new ELFunctionDefinition("myfn", "my_func", 
        MyFuncsClass.class, "myFunc", String.class, Integer.class));
    
    jinjava.getGlobalContext().registerClasses(Class<? extends Importable>... classes);
  5. Configure template error handling strategies

    master

    The ErrorHandlingStrategy interface allows you to define how the Jinjava engine reacts to different types of errors encountered during template interpretation. You can specify distinct behaviors for fatal errors and non-fatal errors using the TemplateErrorTypeHandlingStrategy enum.

    Error Handling Options

    StrategyDescription
    IGNORESilently ignore the error and continue processing.
    ADD_ERRORRecord the error in the engine's error list but continue processing.
    THROW_EXCEPTIONImmediately stop processing and throw an exception.

    Predefined Strategies

    Jinjava provides two convenient static factory methods for common configurations:

    • throwAll(): Configures both fatal and non-fatal errors to use THROW_EXCEPTION.
    • ignoreAll(): Configures both fatal and non-fatal errors to use IGNORE.

    Custom Configuration

    You can use the builder() to create a custom strategy by setting specific behaviors for fatal and non-fatal errors.

    // Use a predefined strategy that throws exceptions for all errors
    ErrorHandlingStrategy strategy = ErrorHandlingStrategy.throwAll();
    
    // Or build a custom strategy manually
    ErrorHandlingStrategy customStrategy = ErrorHandlingStrategy.builder()
        .setFatalErrorStrategy(TemplateErrorTypeHandlingStrategy.THROW_EXCEPTION)
        .setNonFatalErrorStrategy(TemplateErrorTypeHandlingStrategy.IGNORE)
        .build();