### Template with Extends and Include Directives Source: https://context7.com/hubspot/jinjava/llms.txt Demonstrates how templates can utilize Jinjava's 'extends' and 'include' directives for modularity. This example assumes a base template and content to be rendered. ```java String template = "{% extends 'base.html' %}\n" + "{ % block content %}\n" + " {{ page_content }}\n" + "{ % endblock %}"; ``` -------------------------------- ### Include and Import Jinjava Templates Source: https://context7.com/hubspot/jinjava/llms.txt Demonstrates how to include external templates and import macros from other files using Jinjava. Ensure the resource locator is configured to find template files. ```java Jinjava jinjava = new Jinjava(); jinjava.setResourceLocator(new FileLocator(new File("templates/"))); Map context = new HashMap<>(); context.put("page_title", "Home"); context.put("nav_items", Arrays.asList("Home", "About", "Contact")); // Main template using includes and imports String mainTemplate = """ {# Include another template #} {% include 'partials/header.html' %} {# Include with context variables #} {% include 'partials/nav.html' with {'active': 'home'} %} {# Include with ignore missing #} {% include 'partials/optional.html' ignore missing %} {# Import macros from external file #} {% import 'macros/forms.html' as forms %} {{ forms.input('username', placeholder='Enter username') }} {{ forms.button('Submit', type='primary') }} {# From import - import specific macros #} {% from 'macros/ui.html' import card, alert %} {{ card('Title', 'Card content here') }} {{ alert('Warning message', type='warning') }} {# Import with aliasing #} {% from 'macros/ui.html' import card as ui_card %} {{ ui_card('Aliased Card', 'Content') }} """; // partials/header.html String headerPartial = """

{{ page_title }}

"""; // macros/forms.html String formsMacros = """ {% macro input(name, type='text', placeholder='') %} {% endmacro %} {% macro button(label, type='default') %} {% endmacro %} """; String result = jinjava.render(mainTemplate, context); ``` ```java String result = jinjava.render(mainTemplate, context); ``` -------------------------------- ### Implement Custom ResourceLocator for File System Source: https://context7.com/hubspot/jinjava/llms.txt Use FileLocator to load templates from a specified directory on the file system. Ensure the directory exists and contains your template files. ```java import com.hubspot.jinjava.Jinjava; import com.hubspot.jinjava.loader.FileLocator; import java.io.File; // Using FileLocator for file system templates Jinjava jinjava = new Jinjava(); jinjava.setResourceLocator(new FileLocator(new File("/templates"))); ``` -------------------------------- ### Implement Custom Database-Backed ResourceLocator Source: https://context7.com/hubspot/jinjava/llms.txt Create a custom ResourceLocator to load templates from a database. This requires a TemplateRepository to fetch templates by name. Ensure the repository implementation correctly handles template retrieval and potential "not found" exceptions. ```java import com.hubspot.jinjava.Jinjava; import com.hubspot.jinjava.loader.ResourceLocator; import com.hubspot.jinjava.interpret.JinjavaInterpreter; import java.nio.charset.Charset; import java.io.IOException; // Custom database-backed locator public class DatabaseResourceLocator implements ResourceLocator { private final TemplateRepository repository; public DatabaseResourceLocator(TemplateRepository repository) { this.repository = repository; } @Override public String getString(String fullName, Charset encoding, JinjavaInterpreter interpreter) throws IOException { Template template = repository.findByName(fullName); if (template == null) { throw new ResourceNotFoundException("Template not found: " + fullName); } return template.getContent(); } } jinjava.setResourceLocator(new DatabaseResourceLocator(templateRepo)); ``` -------------------------------- ### Basic Template Rendering with Jinjava Source: https://context7.com/hubspot/jinjava/llms.txt Renders a template string with provided context variables. Ensure all necessary imports are included. ```java import com.hubspot.jinjava.Jinjava; import java.util.HashMap; import java.util.Map; // Create Jinjava instance Jinjava jinjava = new Jinjava(); // Set up context variables Map context = new HashMap<>(); context.put("name", "World"); context.put("items", Arrays.asList("apple", "banana", "cherry")); // Render template String template = "Hello, {{ name }}!\n" + "{% for item in items %}\n" + " - {{ item }}\n" + "{% endfor %}"; String result = jinjava.render(template, context); // Output: // Hello, World! // - apple // - banana // - cherry ``` -------------------------------- ### Basic Jinjava Template Rendering Source: https://github.com/hubspot/jinjava/blob/master/README.md This Java code demonstrates how to use Jinjava to render a simple HTML template. It requires the `my-template.html` file to be accessible in the classpath. Ensure you have the necessary Guava and `Resources` dependencies. ```java Jinjava jinjava = new Jinjava(); Map 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); ``` -------------------------------- ### Configure Jinjava with Custom Resource Locator Source: https://github.com/hubspot/jinjava/blob/master/README.md This Java code shows how to configure Jinjava with a custom resource locator. It builds a JinjavaConfig and then sets a custom `MyCustomResourceLocator` on the Jinjava instance. ```java JinjavaConfig config = JinjavaConfig.builder().build(); Jinjava jinjava = new Jinjava(config); jinjava.setResourceLocator(new MyCustomResourceLocator()); ``` -------------------------------- ### Define and Use Macros with Jinjava Source: https://context7.com/hubspot/jinjava/llms.txt Demonstrates defining reusable macros for rendering lists and input fields, and using them within a template. Also shows template inheritance by extending a base HTML structure. ```java Jinjava jinjava = new Jinjava(); // Set up file-based template loading for inheritance jinjava.setResourceLocator(new FileLocator(new File("templates/"))); Map context = new HashMap<>(); context.put("page_title", "Welcome"); context.put("items", Arrays.asList("Item 1", "Item 2", "Item 3")); // Template with macros (can be in same file or imported) String templateWithMacros = """ {# Define a macro #} {# Define a macro #} {% macro render_list(items, class_name='default') %}
    {% for item in items %}
  • {{ item }}
  • {% endfor %}
{% endmacro %} {# Macro with default values #} {% macro input(name, value='', type='text', placeholder='') %} {% endmacro %} {# Use the macros #} {{ render_list(items, 'item-list') }} {{ input('email', type='email', placeholder='Enter email') }} {{ input('password', type='password') }} """; String result = jinjava.render(templateWithMacros, context); ``` ```java // Base template (base.html) String baseTemplate = """ {% block title %}Default Title{% endblock %}
{% block header %}{% endblock %}
{% block content %}{% endblock %}
{% block footer %}Copyright 2024{% endblock %}
""" ``` ```java // Child template extending base String childTemplate = """ {% extends 'base.html' %} {% block title %}{{ page_title }} - My Site{% endblock %} {% block header %} {% endblock %} {% block content %}

{{ page_title }}

Page content goes here

{{ super() }} {# Include parent block content #} {# Include parent block content #} {% endblock %} """ ``` -------------------------------- ### Using Jinjava Built-in Filters Source: https://context7.com/hubspot/jinjava/llms.txt Demonstrates various built-in Jinjava filters for string manipulation, HTML encoding, list operations, object filtering, math, date formatting, and default value handling. Requires Jinjava library and a Map for context. ```java Jinjava jinjava = new Jinjava(); Map context = new HashMap<>(); // String filters context.put("text", "hello world"); context.put("html", "

Hello

"); context.put("items", Arrays.asList("apple", "banana", "cherry")); context.put("users", Arrays.asList( Map.of("name", "Alice", "age", 30), Map.of("name", "Bob", "age", 25), Map.of("name", "Charlie", "age", 35) )); context.put("dict", Map.of("a", 1, "b", 2, "c", 3)); context.put("date", ZonedDateTime.now()); String template = """ {# String manipulation #} {{ text|capitalize }} {# Hello world #} {{ text|title }} {# Hello World #} {{ text|upper }} {# HELLO WORLD #} {{ text|replace('world', 'Java') }} {# hello Java #} {{ 'hello'|center(20) }} {# ' hello ' #} {{ ' hello '|trim }} {# 'hello' #} {# HTML/Encoding #} {{ html|striptags }} {# Hello #} {{ html|escape }} {# <p>Hello</p> #} {{ 'test'|urlencode }} {# test #} {{ 'data'|base64encode }} {# ZGF0YQ== #} {# List operations #} {{ items|join(', ') }} {# apple, banana, cherry #} {{ items|first }} {# apple #} {{ items|last }} {# cherry #} {{ items|length }} {# 3 #} {{ items|reverse|join(', ') }} {# cherry, banana, apple #} {{ items|sort|join(', ') }} {# apple, banana, cherry #} {# Object filtering #} {{ users|map(attribute='name')|join(', ') }} {# Alice, Bob, Charlie #} {{ users|sort(false, false, 'age')|map(attribute='name')|join(', ') }} {{ users|selectattr('age', 'greaterthan', 28)|map(attribute='name')|list }} {# Math and numbers #} {{ 3.7|round }} {# 4 #} {{ 100|filesizeformat }} {# 100 Bytes #} {{ 42|abs }} {# 42 #} {# Date formatting #} {{ date|datetimeformat('%Y-%m-%d') }} {{ date|datetimeformat('%B %d, %Y', 'UTC') }} {# JSON/YAML #} {{ dict|tojson }} {# {"a":1,"b":2,"c":3} #} {{ dict|pprint }} {# Pretty printed JSON #} {# Default values #} {{ missing|default('N/A') }} {# N/A #} {{ ''|default('empty', true) }} {# empty #} """; String result = jinjava.render(template, context); ``` -------------------------------- ### Date and Time Formatting and Manipulation in Jinjava Source: https://context7.com/hubspot/jinjava/llms.txt Shows how to format dates using `datetimeformat`, convert timezones, use built-in date functions like `today()`, convert between Unix timestamps and dates, and perform date arithmetic using `plus_time`, `minus_time`, and `between_times` filters. ```java import com.hubspot.jinjava.Jinjava; import com.hubspot.jinjava.JinjavaConfig; import java.time.ZonedDateTime; import java.time.ZoneId; JinjavaConfig config = JinjavaConfig.newBuilder() .withTimeZone(ZoneId.of("America/New_York")) .withLocale(Locale.US) .build(); Jinjava jinjava = new Jinjava(config); Map context = new HashMap<>(); context.put("event_date", ZonedDateTime.of(2024, 12, 25, 10, 30, 0, 0, ZoneId.of("UTC"))); context.put("timestamp", 1703505000000L); // Unix timestamp in milliseconds String template = """ {# Date formatting with strftime directives #} {# Date formatting with strftime directives #} {{ event_date|datetimeformat('%Y-%m-%d') }} {{ event_date|datetimeformat('%B %d, %Y') }} {{ event_date|datetimeformat('%A, %B %d, %Y at %I:%M %p') }} {# Timezone conversion #} {# Timezone conversion #} {{ event_date|datetimeformat('%Y-%m-%d %H:%M', 'America/Los_Angeles') }} {{ event_date|datetimeformat('%Y-%m-%d %H:%M', 'Europe/London') }} {# Built-in date functions #} {# Built-in date functions #} Today: {{ today() }} Today in timezone: {{ today('America/New_York') }} {# Unix timestamp conversion #} {# Unix timestamp conversion #} {{ unixtimestamp(event_date) }} {# String to date conversion #} {# String to date conversion #} {{ stringToTime('2024-12-25 10:30:00', '%Y-%m-%d %H:%M:%S') }} {{ stringToDate('2024-12-25', '%Y-%m-%d') }} {# Date arithmetic with filters #} {# Date arithmetic with filters #} {{ event_date|plus_time(7, 'days')|datetimeformat('%Y-%m-%d') }} {{ event_date|minus_time(1, 'months')|datetimeformat('%Y-%m-%d') }} {{ between_times(event_date, today(), 'days') }} days until event """; String result = jinjava.render(template, context); ``` -------------------------------- ### Configure Jinjava with Multiple Resource Locators Source: https://github.com/hubspot/jinjava/blob/master/README.md This Java code demonstrates how to configure Jinjava to use multiple resource locators, such as a custom one and a file system locator. A `CascadingResourceLocator` is implicitly used when multiple locators are provided. ```java JinjavaConfig config = JinjavaConfig.builder().build(); Jinjava jinjava = new Jinjava(config); jinjava.setResourceLocator(new MyCustomResourceLocator(), new FileResourceLocator()); ``` -------------------------------- ### Apache 2.0 License Header Source: https://github.com/hubspot/jinjava/blob/master/CONTRIBUTING.md Include this header in all new files to comply with the project's Apache 2.0 license. Ensure it is correctly formatted. ```java /** * 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. */ ``` -------------------------------- ### Generate Jinjava Documentation Source: https://context7.com/hubspot/jinjava/llms.txt Use Jinjava's documentation API to retrieve details about registered filters, tags, and functions. Register custom components before generating documentation. ```java import com.hubspot.jinjava.Jinjava; import com.hubspot.jinjava.doc.JinjavaDoc; import com.hubspot.jinjava.doc.JinjavaDocFilter; import com.hubspot.jinjava.doc.JinjavaDocTag; import com.hubspot.jinjava.doc.JinjavaDocFunction; Jinjava jinjava = new Jinjava(); // Register custom components first jinjava.registerFilter(new SlugifyFilter()); jinjava.registerTag(new PermissionTag()); // Get comprehensive documentation JinjavaDoc doc = jinjava.getJinjavaDoc(); // List all available filters System.out.println("=== Filters ==="); for (JinjavaDocFilter filter : doc.getFilters()) { System.out.println(filter.getName() + ": " + filter.getDesc()); if (filter.getParams() != null) { filter.getParams().forEach(p -> System.out.println(" - " + p.getName() + " (" + p.getType() + "): " + p.getDesc()) ); } } // List all available tags System.out.println("\n=== Tags ==="); for (JinjavaDocTag tag : doc.getTags()) { System.out.println(tag.getName() + ": " + tag.getDesc()); if (tag.getSnippets() != null) { tag.getSnippets().forEach(s -> System.out.println(" Example: " + s.getCode()) ); } } // List all available functions System.out.println("\n=== Functions ==="); for (JinjavaDocFunction fn : doc.getFunctions()) { System.out.println(fn.getName() + ": " + fn.getDesc()); } // Get code editor snippets (TextMate format) String snippets = jinjava.getJinjavaSnippetDoc(); System.out.println("\n=== Editor Snippets ==="); System.out.println(snippets); ``` -------------------------------- ### Jinjava Control Structures for Loops and Conditionals Source: https://context7.com/hubspot/jinjava/llms.txt Illustrates Jinjava's control structures, including for loops with loop variables, conditional statements (if/elif/else), for-else for empty collections, iterating over dictionaries, filtering within loops, and expression tests in conditions. Requires Jinjava library and a Map for context. ```java Jinjava jinjava = new Jinjava(); Map context = new HashMap<>(); context.put("users", Arrays.asList( Map.of("name", "Alice", "active", true, "role", "admin"), Map.of("name", "Bob", "active", false, "role", "user"), Map.of("name", "Charlie", "active", true, "role", "user") )); context.put("settings", Map.of("debug", true, "version", "2.0")); String template = """ {# For loop with loop variables #} {% for user in users %} {{ loop.index }}. {{ user.name }} {% if loop.first %}(First user){% endif %} {% if loop.last %}(Last user){% endif %} Index0: {{ loop.index0 }}, RevIndex: {{ loop.revindex }} {% endfor %} {# Conditional statements #} {% if settings.debug %} Debug mode enabled {% elif settings.version == '1.0' %} Legacy version {% else %} Production mode {% endif %} {# For-else for empty collections #} {% for item in empty_list %} {{ item }} {% else %} No items found {% endfor %} {# Iterating over dictionary #} {% for key, value in settings.items() %} {{ key }}: {{ value }} {% endfor %} {# Filtering in loops #} {% for user in users if user.active %} Active: {{ user.name }} {% endfor %} {# Expression tests in conditions #} {% for user in users %} {% if user.role is equalto 'admin' %} Admin: {{ user.name }} {% endif %} {% if user.name is string_startingwith 'A' %} Name starts with A: {{ user.name }} {% endif %} {% endfor %} """; String result = jinjava.render(template, context); ``` -------------------------------- ### Assign Variable and Include Template Source: https://github.com/hubspot/jinjava/blob/master/src/test/resources/tags/includetag/errors/base.html Demonstrates assigning a value to a variable and including another template file within a Jinjava template. ```jinjava {% set test = 1 + 1 %} {% include "tags/includetag/errors/error.html" %} ``` -------------------------------- ### Create and Register a Custom Permission Tag Source: https://context7.com/hubspot/jinjava/llms.txt Implement a custom tag named 'permission' that conditionally renders content based on user permissions. The tag requires a permission string as a helper and checks against a 'user_permissions' list in the interpreter context. Ensure the 'user_permissions' context variable is populated. ```java import com.hubspot.jinjava.Jinjava; import com.hubspot.jinjava.lib.tag.Tag; import com.hubspot.jinjava.interpret.JinjavaInterpreter; import com.hubspot.jinjava.tree.TagNode; import com.hubspot.jinjava.doc.annotations.JinjavaDoc; import com.hubspot.jinjava.doc.annotations.JinjavaSnippet; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.Arrays; import com.hubspot.jinjava.tree.Node; @JinjavaDoc( value = "Renders content only if user has specified permission", snippets = @JinjavaSnippet( code = "{% permission 'admin' %}\n Admin content here\n{% endpermission %}" ) ) public class PermissionTag implements Tag { @Override public String getName() { return "permission"; } @Override public String interpret(TagNode tagNode, JinjavaInterpreter interpreter) { String requiredPermission = tagNode.getHelpers().trim().replace("'", ""); @SuppressWarnings("unchecked") List userPermissions = (List) interpreter.getContext() .get("user_permissions"); if (userPermissions != null && userPermissions.contains(requiredPermission)) { StringBuilder result = new StringBuilder(); for (Node child : tagNode.getChildren()) { result.append(child.render(interpreter)); } return result.toString(); } return ""; } @Override public String getEndTagName() { return "endpermission"; } } // Register and use Jinjava jinjava = new Jinjava(); jinjava.registerTag(new PermissionTag()); Map context = new HashMap<>(); context.put("user_permissions", Arrays.asList("admin", "editor")); String template = "{% permission 'admin' %}Secret Admin Panel{% endpermission %}"; String result = jinjava.render(template, context); // Output: Secret Admin Panel ``` -------------------------------- ### Initialize HubSpot Variables and Tracking Source: https://github.com/hubspot/jinjava/blob/master/src/test/resources/filter/blog.html This code initializes HubSpot variables and pushes tracking data to the HubSpot analytics object. It sets content type, canonical URL, page ID, and other metadata. This is essential for HubSpot's tracking and personalization features. ```javascript var hsVars = hsVars || {}; hsVars\[ 'language' \] = 'en'; ``` ```javascript var _hsq = _hsq || []; _hsq.push(["setContentType", "listing-page"]); _hsq.push(["setCanonicalUrl", "http:\/\/26191663.hs-sites-eu1.com\/blog"]); _hsq.push(["setPageId", "52304391359"]); _hsq.push(["setContentMetadata", { "contentPageId": 52304391359, "legacyPageId": "52304391359", "contentFolderId": null, "contentGroupId": 52304391358, "abTestId": null, "languageVariantId": 52304391359, "languageCode": "en", }]); ``` ```javascript var hsVars = { ticks: 1666644475431, page_id: 52304391359, content_group_id: 52304391358, portal_id: 26191663, app_hs_base_url: "https://app-eu1.hubspot.com", cp_hs_base_url: "https://cp-eu1.hubspot.com", language: "en", analytics_page_type: "listing-page", analytics_page_id: "52304391359", category_id: 7, folder_id: 0, is_hubspot_user: false } ``` -------------------------------- ### Customizing Jinjava Rendering with JinjavaConfig Source: https://context7.com/hubspot/jinjava/llms.txt Configures Jinjava's rendering behavior using JinjavaConfig. This allows customization of various parameters such as character set, locale, timezone, and output limits. Ensure all necessary imports are included. ```java import com.hubspot.jinjava.Jinjava; import com.hubspot.jinjava.JinjavaConfig; import java.nio.charset.StandardCharsets; import java.time.ZoneId; import java.util.Locale; JinjavaConfig config = JinjavaConfig.newBuilder() .withCharset(StandardCharsets.UTF_8) .withLocale(Locale.US) .withTimeZone(ZoneId.of("America/New_York")) .withMaxRenderDepth(20) .withMaxOutputSize(500000) .withMaxStringLength(100000) .withMaxListSize(10000) .withMaxMapSize(10000) .withRangeLimit(5000) .withTrimBlocks(true) .withLstripBlocks(true) .withFailOnUnknownTokens(false) .withNestedInterpretationEnabled(true) .withEnableRecursiveMacroCalls(false) .withMaxMacroRecursionDepth(10) .build(); Jinjava jinjava = new Jinjava(config); // Use configured Jinjava for rendering Map context = new HashMap<>(); context.put("date", ZonedDateTime.now()); String template = "{{ date|datetimeformat('%B %d, %Y', 'America/New_York') }}"; String result = jinjava.render(template, context); ``` -------------------------------- ### Variable Assignment with Set Tag in Jinjava Source: https://context7.com/hubspot/jinjava/llms.txt Illustrates various ways to assign variables using the `set` tag, including simple assignment, expression assignment, multiple assignments, block assignment, and assignment with filters. Also shows namespace usage for loop variable modification. ```java Jinjava jinjava = new Jinjava(); Map context = new HashMap<>(); context.put("prices", Arrays.asList(10.0, 20.0, 30.0)); context.put("user", Map.of("firstName", "John", "lastName", "Doe")); String template = """ {# Simple assignment #} {# Simple assignment #} {% set greeting = 'Hello' %} {{ greeting }} {# Expression assignment #} {# Expression assignment #} {% set total = prices|sum %} {% set average = total / prices|length %} Total: {{ total }}, Average: {{ average }} {# Multiple assignment #} {# Multiple assignment #} {% set x, y, z = 1, 2, 3 %} Coordinates: {{ x }}, {{ y }}, {{ z }} {# Block assignment (capture rendered content) #} {# Block assignment (capture rendered content) #} {% set full_name %} {{ user.firstName }} {{ user.lastName }} {% endset %} Full Name: {{ full_name|trim }} {# Assignment with filters #} {# Assignment with filters #} {% set slug = 'Hello World'|lower|replace(' ', '-') %} Slug: {{ slug }} {# Namespace for loop variable modification #} {# Namespace for loop variable modification #} {% set ns = namespace(counter=0) %} {% for item in prices %} {% set ns.counter = ns.counter + 1 %} {% endfor %} Counter: {{ ns.counter }} """; String result = jinjava.render(template, context); ``` -------------------------------- ### Create and Register a Custom Slugify Filter Source: https://context7.com/hubspot/jinjava/llms.txt Implement a custom filter named 'slugify' to convert strings into a URL-friendly format. It accepts an optional separator argument. Ensure the input variable is not null before processing. ```java import com.hubspot.jinjava.Jinjava; import com.hubspot.jinjava.lib.filter.Filter; import com.hubspot.jinjava.interpret.JinjavaInterpreter; import com.hubspot.jinjava.doc.annotations.JinjavaDoc; import com.hubspot.jinjava.doc.annotations.JinjavaParam; import com.hubspot.jinjava.doc.annotations.JinjavaSnippet; import java.util.Map; import java.util.HashMap; @JinjavaDoc( value = "Converts a string to slug format", input = @JinjavaParam(value = "value", desc = "String to slugify", required = true), params = @JinjavaParam(value = "separator", defaultValue = "-", desc = "Separator character"), snippets = @JinjavaSnippet(code = "{{ 'Hello World'|slugify }}", output = "hello-world") ) public class SlugifyFilter implements Filter { @Override public String getName() { return "slugify"; } @Override public Object filter(Object var, JinjavaInterpreter interpreter, String... args) { if (var == null) { return null; } String separator = args.length > 0 ? args[0] : "-"; String input = var.toString(); return input.toLowerCase() .replaceAll("[^a-z0-9\\s]", "") .replaceAll("\\s+", separator) .trim(); } } // Register the filter Jinjava jinjava = new Jinjava(); jinjava.registerFilter(new SlugifyFilter()); // Use in template Map context = new HashMap<>(); context.put("title", "Hello World! This is a Test"); String result = jinjava.render("{{ title|slugify }}", context); // Output: hello-world-this-is-a-test ``` -------------------------------- ### Register Custom Jinja Elements in Jinjava Source: https://github.com/hubspot/jinjava/blob/master/README.md This Java code snippet illustrates how to register custom tags, filters, and functions with the Jinjava global context. It shows the methods for registering a custom tag, filter, and a static function using `ELFunctionDefinition`. ```java // define a custom tag implementing com.hubspot.jinjava.lib.Tag jinjava.getGlobalContext().registerTag(new MyCustomTag()); // define a custom filter implementing com.hubspot.jinjava.lib.Filter jinjava.getGlobalContext().registerFilter(new MyAwesomeFilter()); // define a custom public static function (this one will bind to myfn:my_func('foo', 42)) jinjava.getGlobalContext().registerFunction(new ELFunctionDefinition("myfn", "my_func", MyFuncsClass.class, "myFunc", String.class, Integer.class); // define any number of classes which extend Importable jinjava.getGlobalContext().registerClasses(Class... classes); ``` -------------------------------- ### Load Facebook SDK for Social Plugins Source: https://github.com/hubspot/jinjava/blob/master/src/test/resources/filter/blog.html This snippet asynchronously loads the Facebook JavaScript SDK. It is required for using Facebook social plugins like Like buttons or embedded posts. Ensure this script is included to enable Facebook integrations. ```javascript (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&status=0"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); ``` -------------------------------- ### Register Custom Java Functions for Jinjava Templates Source: https://context7.com/hubspot/jinjava/llms.txt Define and register custom Java methods to be used as functions within Jinjava templates. Ensure the method signature matches the expected parameter types for registration. ```java import com.hubspot.jinjava.Jinjava; import com.hubspot.jinjava.lib.fn.ELFunctionDefinition; import com.hubspot.jinjava.doc.annotations.JinjavaDoc; import com.hubspot.jinjava.doc.annotations.JinjavaParam; import java.util.Locale; import java.util.Map; import java.util.HashMap; public class CustomFunctions { @JinjavaDoc( value = "Formats a number as currency", params = { @JinjavaParam(value = "amount", type = "number", required = true), @JinjavaParam(value = "currency", defaultValue = "USD") } ) public static String formatCurrency(Number amount, String currency) { if (amount == null) return ""; java.text.NumberFormat formatter = java.text.NumberFormat.getCurrencyInstance(); if ("EUR".equals(currency)) { formatter = java.text.NumberFormat.getCurrencyInstance(Locale.GERMANY); } return formatter.format(amount.doubleValue()); } public static String repeat(String text, int times) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < times; i++) { sb.append(text); } return sb.toString(); } } // Register functions Jinjava jinjava = new Jinjava(); jinjava.registerFunction(new ELFunctionDefinition( "fn", // namespace "currency", // function name CustomFunctions.class, // class containing method "formatCurrency", // method name Number.class, String.class // parameter types )); jinjava.registerFunction(new ELFunctionDefinition( "fn", "repeat", CustomFunctions.class, "repeat", String.class, int.class )); // Use in templates Map context = new HashMap<>(); context.put("price", 99.99); String template = "Price: {{ fn:currency(price, 'USD') }} " + "{{ fn:repeat('*', 5) }}"; String result = jinjava.render(template, context); // Output: // Price: $99.99 // ***** ``` -------------------------------- ### Track Website Performance with XMLHttpRequest Source: https://github.com/hubspot/jinjava/blob/master/src/test/resources/filter/blog.html This snippet sends performance data to a HubSpot endpoint using XMLHttpRequest. It captures network information and page timing metrics. Ensure the script runs after the window has loaded. ```javascript (function () { window.addEventListener('load', function () { setTimeout(function () { var xhr = new XMLHttpRequest(); xhr.open('POST', '/\_hcms/perf', true /\*async\* /); xhr.setRequestHeader("Content-type", "application/json"); xhr.onreadystatechange = function () { // do nothing. }; var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection; function populateNetworkInfo(name, connection, info) { if (name in connection) { info\[name\] = connection\[name\]; } } var networkInfo = {}; if (connection) { \[ 'type', 'effectiveType', 'downlink', 'rtt' \].forEach(function(name) { populateNetworkInfo(name, connection, networkInfo); }); } var perfData = { url: location.href, portal: 26191663, content: 52304391359, group: -1, connection: networkInfo, timing: performance.timing }; xhr.send(JSON.stringify(perfData)); }, 3000); // Execute this 3 seconds after onload. }); })(); ``` -------------------------------- ### CSS for Header Styling Source: https://github.com/hubspot/jinjava/blob/master/src/test/resources/filter/truncatehtml/long-content-with-tags.html This CSS targets a header element to style its main heading link. Ensure the HTML structure matches the selector. ```css #header h1 a { display: block; width: 300px; height: 80px; } ``` -------------------------------- ### Apply Subtract Filter Source: https://github.com/hubspot/jinjava/blob/master/src/test/resources/tags/includetag/errors/base.html Shows how to apply the 'subtract' filter to a string in Jinjava. Note that this filter is typically used with numeric types. ```jinjava {{ "test"|subtract(1) }} ``` -------------------------------- ### Generate Sequences and Control Loops in Jinjava Source: https://context7.com/hubspot/jinjava/llms.txt Utilize the range function to generate integer sequences and loop controls like break and continue to manage iteration. The batch and slice filters can be used for data manipulation. ```java Jinjava jinjava = new Jinjava(); Map context = new HashMap<>(); String template = """ {# Range function - generates list of integers #} {% for i in range(5) %}{{ i }} {% endfor %} {# Output: 0 1 2 3 4 #} {% for i in range(1, 6) %}{{ i }} {% endfor %} {# Output: 1 2 3 4 5 #} {% for i in range(0, 10, 2) %}{{ i }} {% endfor %} {# Output: 0 2 4 6 8 #} {% for i in range(10, 0, -2) %}{{ i }} {% endfor %} {# Output: 10 8 6 4 2 #} {# Loop controls (break and continue) #} {% for i in range(10) %} {% if i == 5 %}{% break %}{% endif %} {{ i }} {% endfor %} {# Output: 0 1 2 3 4 #} {% for i in range(10) %} {% if i % 2 == 0 %}{% continue %}{% endif %} {{ i }} {% endfor %} {# Output: 1 3 5 7 9 #} {# Batch filter for chunking #} {% for row in range(9)|batch(3) %} {% for col in row %}{{ col }}{% endfor %} {% endfor %} {# Slice filter #} {% for column in items|slice(3) %}
{% for item in column %}{{ item }}{% endfor %}
{% endfor %} """; String result = jinjava.render(template, context); ``` -------------------------------- ### Add Jinjava Dependency to Maven Project Source: https://github.com/hubspot/jinjava/blob/master/README.md Include this XML snippet in your Maven project's pom.xml to add the Jinjava library as a dependency. Replace {LATEST_VERSION} with the actual latest version. ```xml com.hubspot.jinjava jinjava { LATEST_VERSION } ``` -------------------------------- ### Control Output Escaping with Jinjava Source: https://context7.com/hubspot/jinjava/llms.txt Manage output escaping and preserve raw template syntax using Jinjava's raw, autoescape, and safe filters. Use 'escapejs' for JavaScript and 'tojson' for JSON output. ```java Jinjava jinjava = new Jinjava(); Map context = new HashMap<>(); context.put("user_input", ""); context.put("html_content", "Bold text"); String template = """ {# Raw tag - preserve Jinja syntax without processing #} {% raw %} This will show literal {{ variable }} syntax {% for item in items %}{{ item }}{% endfor %} {% endraw %} {# Autoescape control #} {% autoescape true %} User input (escaped): {{ user_input }} {% endautoescape %} {% autoescape false %} HTML content (unescaped): {{ html_content }} {% endautoescape %} {# Safe filter to mark content as safe #} {{ html_content|safe }} {# Force escape even when autoescape is off #} {{ html_content|escape }} {{ html_content|e }} {# Short alias #} {# Escape for JavaScript #} {# Escape for JSON #} """; String result = jinjava.render(template, context); ``` -------------------------------- ### Add Jinjava Dependency for Java 7 Source: https://github.com/hubspot/jinjava/blob/master/README.md Use this Maven dependency configuration if your project is still on Java 7. This specifies a version of Jinjava compatible with Java 7. ```xml com.hubspot.jinjava jinjava 2.0.11-java7 ``` -------------------------------- ### Register Custom Expression Tests for Jinjava Source: https://context7.com/hubspot/jinjava/llms.txt Implement custom expression tests to enhance conditional logic in Jinjava templates. The `evaluate` method determines the test's outcome. ```java import com.hubspot.jinjava.Jinjava; import com.hubspot.jinjava.lib.exptest.ExpTest; import com.hubspot.jinjava.interpret.JinjavaInterpreter; import com.hubspot.jinjava.doc.annotations.JinjavaDoc; import com.hubspot.jinjava.doc.annotations.JinjavaSnippet; import java.util.regex.Pattern; import java.util.Map; import java.util.HashMap; @JinjavaDoc( value = "Returns true if the string is a valid email address", snippets = { @JinjavaSnippet(code = "{% if email is email %}Valid{% endif %}") } ) public class IsEmailExpTest implements ExpTest { private static final Pattern EMAIL_PATTERN = Pattern.compile("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$"); @Override public String getName() { return "email"; } @Override public boolean evaluate(Object var, JinjavaInterpreter interpreter, Object... args) { if (var == null) return false; return EMAIL_PATTERN.matcher(var.toString()).matches(); } } @JinjavaDoc(value = "Returns true if value is within the specified range") public class IsWithinRangeExpTest implements ExpTest { @Override public String getName() { return "within_range"; } @Override public boolean evaluate(Object var, JinjavaInterpreter interpreter, Object... args) { if (var == null || args.length < 2) return false; double value = ((Number) var).doubleValue(); double min = ((Number) args[0]).doubleValue(); double max = ((Number) args[1]).doubleValue(); return value >= min && value <= max; } } // Register and use Jinjava jinjava = new Jinjava(); jinjava.registerExpTest(new IsEmailExpTest()); jinjava.registerExpTest(new IsWithinRangeExpTest()); Map context = new HashMap<>(); context.put("email", "user@example.com"); context.put("score", 85); String template = "{% if email is email %}Valid email{% endif %}\n" + "{% if score is within_range(0, 100) %}Valid score{% endif %}"; String result = jinjava.render(template, context); // Output: // Valid email // Valid score ``` -------------------------------- ### RenderResult for Error Handling in Jinjava Source: https://context7.com/hubspot/jinjava/llms.txt Utilizes renderForResult to obtain rendering output along with metadata, including any errors encountered during the process. This method is useful for debugging and understanding rendering issues. ```java import com.hubspot.jinjava.Jinjava; import com.hubspot.jinjava.interpret.RenderResult; import com.hubspot.jinjava.interpret.TemplateError; import java.util.HashMap; import java.util.Map; Jinjava jinjava = new Jinjava(); Map context = new HashMap<>(); context.put("user", null); String template = "Hello {{ user.name }}!"; RenderResult result = jinjava.renderForResult(template, context); // Get rendered output String output = result.getOutput(); // Check for errors if (result.hasErrors()) { for (TemplateError error : result.getErrors()) { System.out.println("Error: " + error.getMessage()); System.out.println("Line: " + error.getLineno()); System.out.println("Severity: " + error.getSeverity()); } } // Access resolved expressions and context context = result.getContext().getSessionBindings(); ``` -------------------------------- ### Load Twitter Widgets Script Source: https://github.com/hubspot/jinjava/blob/master/src/test/resources/filter/blog.html This code snippet loads the Twitter Widgets JavaScript file, enabling the use of Twitter buttons and embedded timelines on the page. It ensures that Twitter's social features are correctly initialized. ```javascript !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.