### Basic Function Call Example Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/macros.txt Illustrates a simple function call with parameters. No specific setup is required beyond defining the function. ```ftl Home Kilroy was here. ``` -------------------------------- ### FreeMarker String Padding Examples Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins2.txt Shows examples of string padding with spaces and hyphens. These are useful for formatting output to align text. ```ftl [ ] [ a] [ ab] [ abc] [ abcd] [abcde] [abcdef] [abcdefg] [abcdefgh] [-----] [----a] [---ab] [--abc] [-abcd] [abcde] [abcdef] [abcdefg] [abcdefgh] [.oO.oO.o] [.oO.oO.a] [.oO.oOab] [.oO.oabc] [.oO.abcd] [.oOabcde] [.oabcdef] [.abcdefg] [abcdefgh] [abcdefghi] [abcdefghij] [] [/] [/\\] [/\] [/\] [/\] [/\] [/\] ``` ```ftl [ ] [a ] [ab ] [abc ] [abcd ] [abcde] [abcdef] [abcdefg] [abcdefgh] [-----] [a----] [ab---] [abc--] [abcd-] [abcde] [abcdef] [abcdefg] [abcdefgh] [.oO.oO.o] [aoO.oO.o] [abO.oO.o] [abc.oO.o] [abcdoO.o] [abcdeO.o] [abcdef.o] [abcdefgo] [abcdefgh] [abcdefghi] [abcdefghij] [] [/] [/\\] [/\] [/\] [/\] [/\] [/\] ``` -------------------------------- ### Uppercase Conversion Example Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins1.txt Shows a string converted to uppercase. Simple demonstration of case conversion. ```text FOOBAR ``` -------------------------------- ### String Matching Example Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins1.txt Shows examples of string matching, highlighting specific phrases within a larger text. Useful for pattern recognition. ```text the beginning the sacred beginning the Heavens the sacred Heavens The Earth The sacred Earth ``` -------------------------------- ### Default Constructor Example Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins1.txt Illustrates the default constructor behavior for a variable or object. Shows initial or default values. ```ftl default constructor 1 xxx xxx:yyy ``` -------------------------------- ### Whitespace and Concatenation Example Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins1.txt Illustrates how whitespace is handled and strings are concatenated. Shows basic string manipulation. ```text foo bar baz foobar ``` -------------------------------- ### Entire Input Match Example 3 in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins-regexps-matches.txt A simple example showing a boolean 'false' result for an entire input match. ```ftl Matches: false ``` -------------------------------- ### Different Entire Input and Substring Matches Example 2 in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins-regexps-matches.txt Another example of distinct entire input and substring matches, highlighting captured groups. ```ftl 123 - M: 1 (Gs: 1) - M: 2 (Gs: 2) - M: 3 (Gs: 3) ``` -------------------------------- ### Simple Tag Example Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-javax-servlet/src/test/resources/freemarker/ext/jsp/webapps/tldDiscovery/WEB-INF/expected/test1.txt Demonstrates the basic usage of a simple tag within FreeMarker templates. ```ftl enter TestSimpleTag simpletag1 invoking body i=0 foo exit TestSimpleTag simpletag1 ``` -------------------------------- ### HTML Table Example Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-javax-servlet/src/test/resources/freemarker/ext/jsp/webapps/tldDiscovery/WEB-INF/expected/test1.txt A sample HTML table structure. ```html
Name Age Maried
Joe 30 true
Fred 25 false
Emma 28 true
``` -------------------------------- ### Build Native Image with Gradle Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-test-graalvm-native/README.md Use this command to compile the FreeMarker test project into a GraalVM native image. Ensure GraalVM is installed and JAVA_HOME is set correctly. ```shell ./gradlew :freemarker-test-graalvm-native:nativeCompile ``` -------------------------------- ### Generate FreeMarker Online Manual Source: https://github.com/apache/freemarker/blob/2.3-gae/README.md Generates the online manual for FreeMarker, including a Pagefind index. Requires Node.js to be installed. The output is placed in the 'docs' directory of the website. ```bash ./gradlew manualOnline ``` -------------------------------- ### Variable Scope Example Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-javax-servlet/src/test/resources/freemarker/ext/jsp/webapps/basic/WEB-INF/expected/attributes-2.3.22-future.txt Shows how variables are set and retrieved across different scopes (page, request, session, application). ```ftl a1: - any:a1 was null, set to 0 a1: 0 page:a1 was 0, set to 1 a1: 1 request:a1 was null, set to 2 session:a1 was null, set to 3 application:a1 was null, set to 4 Request.a1: 2 Session.a1: 3 Application.a1: 4 a1: 1 page:a1 was 1, set to null a1: 2 request:a1 was 2, set to null a1: 3 session:a1 was 3, set to null a1: 4 application:a1 was 4, set to null a1: - ``` ```ftl a2: - application:a2 was null, set to 4 a2: 4 session:a2 was null, set to 3 a2: 3 request:a2 was null, set to 2 a2: 2 page:a2 was null, set to 1 a2: 1 ``` ```ftl G1 page:a1 was G1, set to P1 P1 ``` ```ftl G2 page:a2 was G2, set to P2 P2 ``` -------------------------------- ### HTML Structure with Other Hits Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/list3.txt Similar to the previous example, but uses a different class name 'hitOther' for the items. ```HTML
a
b
``` -------------------------------- ### Recursive Macro Call Example Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/macros.txt Demonstrates a recursive macro call. This example shows how a macro can call itself, typically used for iterative or tree-like structures. The output is a sequence of numbers. ```ftl 0 1 2 3 ``` -------------------------------- ### Entire Input Match Example 1 in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins-regexps-matches.txt Shows a full input match with named groups and captured sub-groups. ```ftl - M: L16 - G: L16 - G: 1 - G: 6 - M: L27 - G: L27 - G: 2 - G: 7 - M: L38 - G: L38 - G: 3 - G: 8 - M: L49 - G: L49 - G: 4 - G: 9 firstGS was: L16, 1, 6 ``` -------------------------------- ### Entire Input Match Example 2 in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins-regexps-matches.txt A boolean match indicating success, followed by captured groups. ```ftl Matches: true - G: x12 - G: 1 - G: 2 As list: - M: x12 - G: x12 - G: 1 - G: 2 Groups again: - G: x12 - G: 1 - G: 2 ``` -------------------------------- ### Different Entire Input and Substring Matches Example 1 in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins-regexps-matches.txt Shows distinct matches for entire input and substrings, with captured groups for each match. ```ftl 123, 123 - M: 1 (Gs: 1, 1) - M: 2 (Gs: 2, 2) - M: 3 (Gs: 3, 3) ``` -------------------------------- ### Display Numbers in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/arithmetic.txt Shows how numbers are displayed by default in FreeMarker. No specific setup is required. ```ftl 3.234 ``` ```ftl 2.00 ``` ```ftl 0.6172500000000000000000000000000000000000 ``` ```ftl 1.620089104901 ``` ```ftl 1.6201 ``` -------------------------------- ### Array of Tuples Example Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/list3.txt Illustrates a nested array structure, potentially representing coordinates or multi-dimensional data. ```FreeMarker [ [(11@0, 11@0), (11@0, 22@1), (11@0, 33@2)], [(22@1, 11@0), (22@1, 22@1), (22@1, 33@2)], [(33@2, 11@0), (33@2, 22@1), (33@2, 33@2)] ] ``` -------------------------------- ### Entire Input Match Example 4 in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins-regexps-matches.txt A simple boolean match indicating success, followed by captured groups. ```ftl Matches: true - G: x12 - G: 1 - G: 2 ``` -------------------------------- ### Substring Extraction Example Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins1.txt Demonstrates extracting specific parts of a string. Useful for isolating data or specific information. ```text In the beginning, God created the Heavens and The Earth. beginning the Heavens and The Earth. ``` -------------------------------- ### Get String Length Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins1.txt Returns the number of characters in a string. Useful for validation or display. ```ftl length: 71 ``` -------------------------------- ### Iterator to List Mode Transition (Variant 2) in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins-regexps-matches.txt Another example of transitioning from iterator mode to list mode, with items displayed individually. ```ftl [L16][L27][L38][L49] [L16]/4[L27]/4[L38]/4[L49]/4 ``` -------------------------------- ### FreeMarker Output Formats and Auto-Escaping Configuration Source: https://context7.com/apache/freemarker/llms.txt Configures FreeMarker's output formats, including associating file extensions with formats and enabling auto-escaping for security. Shows template examples with different escaping behaviors. ```java import freemarker.template.*; import freemarker.core.*; import java.io.*; import java.util.*; Configuration cfg = new Configuration(Configuration.VERSION_2_3_32); // Associate file extensions with output formats cfg.setRecognizeStandardFileExtensions(true); // .ftlh -> HTML (auto-escaping enabled) // .ftlx -> XML (auto-escaping enabled) // .ftl -> Plain text (no auto-escaping) // Or set default output format cfg.setOutputFormat(HTMLOutputFormat.INSTANCE); // Enable auto-escaping policy cfg.setAutoEscapingPolicy(Configuration.ENABLE_IF_DEFAULT_AUTO_ESCAPING_POLICY); // Register custom output formats cfg.setRegisteredCustomOutputFormats(Arrays.asList( new CombinedMarkupOutputFormat("HTML_JS", HTMLOutputFormat.INSTANCE, JavaScriptOutputFormat.INSTANCE) )); // Template example showing escaping: String htmlTemplate = """ <#-- Auto-escapes HTML special characters -->

User input: ${userInput}

<#-- Disable escaping for trusted markup -->
${trustedHtml?no_esc}
<#-- Different escaping for JavaScript context --> """; // Data with potentially dangerous content Map data = new HashMap<>(); data.put("userInput", ""); data.put("trustedHtml", "Safe HTML"); data.put("userName", "O'Brien"); Template template = new Template("test", htmlTemplate, cfg); StringWriter out = new StringWriter(); template.process(data, out); // Output (HTML escaped automatically): //

User input: <script>alert('xss')</script>

//
Safe HTML
// "; ``` -------------------------------- ### Subtract Operator in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/comparisons.txt Demonstrates the subtraction operator (-) in FreeMarker for finding the difference between two numeric values. The example shows subtracting one number from another. ```ftl op3 = op1 - op2 ``` -------------------------------- ### Add Operator in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/comparisons.txt Shows the addition operator (+) in FreeMarker for combining numeric values. The example demonstrates adding two numbers and storing the result in a third variable. ```ftl op3 = op1 + op2 ``` -------------------------------- ### Extract Last Character in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/lastcharacter.txt Use the built-in `?last_char` to get the last character of a string. This example shows its usage with a hardcoded string. ```ftl ${message?last_char} ``` -------------------------------- ### Build FreeMarker JAR with Gradle Source: https://github.com/apache/freemarker/blob/2.3-gae/README.md Use this command in the project root to build the freemarker.jar file. Gradle will automatically download dependencies. ```bash ./gradlew jar ``` -------------------------------- ### Initialize FreeMarker Configuration Source: https://context7.com/apache/freemarker/llms.txt Initialize the Configuration class once at application startup. Specify the version for predictable behavior and set template loading paths. Recommended settings for encoding, exception handling, and null loop variables are included. ```java import freemarker.template.*; import freemarker.cache.*; import java.io.*; import java.util.*; // Create configuration - do this ONCE at application startup Configuration cfg = new Configuration(Configuration.VERSION_2_3_32); // Set template loading directory cfg.setDirectoryForTemplateLoading(new File("/path/to/templates")); // Or load from classpath // cfg.setClassForTemplateLoading(MyClass.class, "templates"); // Recommended settings cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); cfg.setLogTemplateExceptions(false); cfg.setWrapUncheckedExceptions(true); cfg.setFallbackOnNullLoopVariable(false); // Optional: Set locale and time zone cfg.setLocale(Locale.US); cfg.setTimeZone(TimeZone.getTimeZone("America/New_York")); // Optional: Configure caching cfg.setCacheStorage(new SoftCacheStorage()); cfg.setTemplateUpdateDelayMilliseconds(5000); // Check for updates every 5 seconds // Store cfg as singleton - reuse throughout application ``` -------------------------------- ### Build Distribution Artifacts with Gradle Source: https://github.com/apache/freemarker/blob/2.3-gae/README.md Run this command to build the distribution artifacts (tgz files) for FreeMarker. ```bash ./gradlew build ``` -------------------------------- ### Tag Loading from MetaInfTldSources (init-param) Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-javax-servlet/src/test/resources/freemarker/ext/jsp/webapps/tldDiscovery/WEB-INF/expected/test1.txt Shows tag loading from 'MetaInfTldSources' configured via an init-param. ```text Executed TestSimpleTag3 ``` -------------------------------- ### Basic Arithmetic and Comparisons in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins2.txt Demonstrates simple arithmetic and comparison operations. These are fundamental for basic template logic. ```ftl 1 = 1 5 = 5 0 = 0 ``` ```ftl 5 = 5 1 = 1 7 = 7 ``` ```ftl true = true false = false true = true ``` ```ftl true = true false = false true = true ``` ```ftl true = true true = true true = true false = false true = true ``` -------------------------------- ### Run FreeMarker Native Executable Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-test-graalvm-native/README.md Execute the compiled native image to see the FreeMarker GraalVM demo output. Adjust path separators for Windows. ```shell ./freemarker-test-graalvm-native/build/native/nativeCompile/freemarker-test-graalvm-native ``` -------------------------------- ### Serve Local Website Content with HTTP Source: https://github.com/apache/freemarker/blob/2.3-gae/README.md When testing the generated static website locally, use this command to serve the content via HTTP(S). This is necessary for the search functionality to work due to browser security restrictions on 'file:' URLs. ```bash npx http-server ``` -------------------------------- ### Publish FreeMarker to Local Maven Repository Source: https://github.com/apache/freemarker/blob/2.3-gae/README.md Use this command to simulate deployment to Maven Central and check the output in the local deployment directory. ```bash ./gradlew publishAllPublicationsToLocalRepository ``` -------------------------------- ### Java Servlet Integration with FreeMarker Source: https://context7.com/apache/freemarker/llms.txt Demonstrates how to integrate FreeMarker into a Java Servlet for dynamic web content generation. Includes servlet initialization and template processing. ```java import freemarker.template.*; import freemarker.ext.servlet.*; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class ProductServlet extends HttpServlet { private Configuration cfg; @Override public void init() throws ServletException { // Initialize FreeMarker once at servlet startup cfg = new Configuration(Configuration.VERSION_2_3_32); cfg.setServletContextForTemplateLoading( getServletContext(), "/WEB-INF/templates" ); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html; charset=UTF-8"); // Build data model Map model = new HashMap<>(); model.put("products", getProductsFromDatabase()); model.put("user", request.getUserPrincipal()); model.put("contextPath", request.getContextPath()); // Get and process template try { Template template = cfg.getTemplate("products.ftlh"); template.process(model, response.getWriter()); } catch (TemplateException e) { throw new ServletException("Template processing failed", e); } } private List> getProductsFromDatabase() { // Fetch products from database return Arrays.asList( Map.of("id", 1, "name", "Widget", "price", 29.99), Map.of("id", 2, "name", "Gadget", "price", 49.99) ); } } ``` ```xml freemarker freemarker.ext.servlet.FreemarkerServlet TemplatePath /WEB-INF/templates ``` -------------------------------- ### List Mode Iteration in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins-regexps-matches.txt Demonstrates basic list iteration in FreeMarker. Each item is displayed once. ```ftl [L16][L27][L38][L49] [L16][L27][L38][L49] ``` -------------------------------- ### Generate Offline Documentation with Gradle Source: https://github.com/apache/freemarker/blob/2.3-gae/README.md Commands to generate offline documentation for FreeMarker using Gradle. ```bash ./gradlew javadoc ``` ```bash ./gradlew manualOffline ``` -------------------------------- ### Publish FreeMarker to Apache Maven Repository Source: https://github.com/apache/freemarker/blob/2.3-gae/README.md This command publishes artifacts to the Apache Maven Repository. Ensure necessary Gradle properties like signing and credentials are set in gradle.properties or passed as arguments. ```bash .\gradlew publish ``` -------------------------------- ### Run FreeMarker Tests with Gradle Source: https://github.com/apache/freemarker/blob/2.3-gae/README.md Execute this command to run all JUnit tests and other checks for FreeMarker. Avoid the 'test' task as it only runs tests for the 'core' source set. ```bash ./gradlew check ``` -------------------------------- ### String as Word List Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins1.txt Demonstrates splitting a string into a list of words based on whitespace. Useful for tokenizing text. ```ftl word_list: - dieBugsDie! - * - vazzZE - 123456 - --cdc-- - --<<--@ - x - ${"kigyo"?upper_case} ``` -------------------------------- ### Tag Loading from Mapped Relative URL Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-javax-servlet/src/test/resources/freemarker/ext/jsp/webapps/tldDiscovery/WEB-INF/expected/test1.txt Demonstrates loading tags using a mapped relative URL. ```text Executed TestSimpleTag2 ``` -------------------------------- ### Hash Assignment and Update Test Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/hashliteral.txt Demonstrates assigning a hash, updating its values, and repeating the output. Note the behavior with missing keys during updates. ```ftl <#assign test23 = {"a": "Hello, world!", "b": "hello all"}> ${test23.a} ${test23.b} ${test23.c!1} ``` ```ftl <#assign test23 = {"a": "Hello, world!", "b": "hello all"}> ${test23.a} ${test23.b} ${test23.c!1} ``` -------------------------------- ### Map with Nested Structures and Comments Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/listhash.txt Demonstrates a more complex map structure with nested elements and comments, showing how to define key-value pairs within a map. ```ftl a @ 0, 1 aa = 11 @ 0 // inside a @ 0, 1 a @ 0, 1 -- b @ 1, 2 ba = 21 @ 0 // inside b @ 1, 2 bb = 22 @ 1 // inside b @ 1, 2 b @ 1, 2 -- c @ 2, 0 c @ 2, 0 -- ``` -------------------------------- ### Function Call with Different Parameters Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/macros.txt Shows another function call with different parameters, demonstrating flexibility. Ensure the function definition supports these parameters. ```ftl About Us Kilroy was here. ``` -------------------------------- ### Test Tag Loading from WEB-INF/lib/*.jar Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-javax-servlet/src/test/resources/freemarker/ext/jsp/webapps/tldDiscovery/WEB-INF/expected/test-noClasspath.txt This snippet shows the execution of a tag's doStartTag and doEndTag methods when loaded from the WEB-INF/lib/*.jar directory. ```Java TestTag3.doStartTag() called here TestTag3.doEndTag() called here ``` -------------------------------- ### List with Items (Multiple Items) Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/list2.txt Renders list items enclosed in square brackets, with each item on a new line. This is useful for array-like output. ```ftl [ aardvark bear cat dog ] ``` -------------------------------- ### Variable Scope Demonstration in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-javax-servlet/src/test/resources/freemarker/ext/jsp/webapps/basic/WEB-INF/expected/attributes.txt Illustrates variable scope behavior in FreeMarker. Variables are set in different scopes (request, session, application, page) and their values are shown as they are accessed. ```ftl a1: - any:a1 was null, set to 0 a1: 0 page:a1 was 0, set to 1 a1: 1 request:a1 was null, set to 2 session:a1 was null, set to 3 application:a1 was null, set to 4 Request.a1: 2 Session.a1: 3 Application.a1: 4 a1: 1 page:a1 was 1, set to null a1: 2 request:a1 was 2, set to null a1: 3 session:a1 was 3, set to null a1: 4 application:a1 was 4, set to null a1: - ``` ```ftl a2: - application:a2 was null, set to 4 a2: 4 session:a2 was null, set to 3 a2: 3 request:a2 was null, set to 2 a2: 2 page:a2 was null, set to 1 a2: 1 ``` ```ftl G1 page:a1 was G1, set to P1 P1 ``` ```ftl G2 page:a2 was G2, set to P2 P2 ``` -------------------------------- ### Test Tag Loading from web.xml-mapped JAR Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-javax-servlet/src/test/resources/freemarker/ext/jsp/webapps/tldDiscovery/WEB-INF/expected/test-noClasspath.txt This snippet demonstrates the execution of a tag's doStartTag and doEndTag methods when loaded from a web.xml-mapped JAR. ```Java TestTag2.doStartTag() called here TestTag2.doEndTag() called here ``` -------------------------------- ### List with Items (Single Item) Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/list2.txt Renders a single item enclosed in square brackets. ```ftl [ aardvark ] ``` -------------------------------- ### Numbers in Hashes Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/number-literal.txt Demonstrates accessing values from a hash using number literals as keys. This shows how numbers can be used to index into hash structures. ```ftl twelve twelve twelve ``` -------------------------------- ### FreeMarker Processing Directives Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/xml.txt Demonstrates the usage of custom directives 'firstPi' and 'secondPi' within a FreeMarker template. Ensure these directives are properly defined and available in your FreeMarker configuration. ```ftl firstPi customKey="something" secondPi secondPiData 2 p customKey="something" ``` -------------------------------- ### HTML Structure with Hits Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/list3.txt Demonstrates basic HTML structure for displaying items, with a class 'hit'. ```HTML
a
b
``` -------------------------------- ### Existence and Safe Navigation in FreeMarker Source: https://context7.com/apache/freemarker/llms.txt Use the '!' operator for default values when a variable is missing or null, and '??' to check for existence. Safe navigation with '!' prevents errors when accessing properties of potentially null objects. ```ftl ${missingVar!} ``` ```ftl ${missingVar!"default"} ``` ```ftl ${value??} ``` ```ftl <#if value??>Value exists ``` ```ftl ${obj.prop!} ``` -------------------------------- ### Create Template from String in Java Source: https://context7.com/apache/freemarker/llms.txt Use this to dynamically generate templates from string content. Ensure the FreeMarker version is correctly configured. ```java import freemarker.template.*; import java.io.*; import java.util.*; Configuration cfg = new Configuration(Configuration.VERSION_2_3_32); cfg.setDefaultEncoding("UTF-8"); // Create template from string String templateStr = """

${title}

<#list items as item>

${item_index + 1}. ${item}

"""; Template template = new Template("inline", templateStr, cfg); // Process the template Map data = new HashMap<>(); data.put("title", "My List"); data.put("items", Arrays.asList("First", "Second", "Third")); StringWriter out = new StringWriter(); template.process(data, out); System.out.println(out.toString()); ``` -------------------------------- ### Configure FreeMarker Object Wrapper Source: https://context7.com/apache/freemarker/llms.txt Set up how Java objects are wrapped for template access. Use DefaultObjectWrapper for general use or BeansWrapper for full bean exposure. Custom wrappers can handle unknown types. ```java import freemarker.template.*; import freemarker.ext.beans.*; import java.util.*; Configuration cfg = new Configuration(Configuration.VERSION_2_3_32); // Use DefaultObjectWrapper (recommended) DefaultObjectWrapper wrapper = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_32) .build(); cfg.setObjectWrapper(wrapper); // Or use BeansWrapper for full Java bean exposure BeansWrapper beansWrapper = new BeansWrapperBuilder(Configuration.VERSION_2_3_32) .build(); cfg.setObjectWrapper(beansWrapper); // Expose static methods of a class beansWrapper.setExposureLevel(BeansWrapper.EXPOSE_ALL); cfg.setSharedVariable("Math", beansWrapper.getStaticModels().get("java.lang.Math")); cfg.setSharedVariable("Integer", beansWrapper.getStaticModels().get("java.lang.Integer")); // In template: // ${Math.sqrt(16)} --> 4.0 // ${Math.max(5, 10)} --> 10 // ${Integer.MAX_VALUE} --> 2147483647 // Create custom wrapper for specific types public class MyObjectWrapper extends DefaultObjectWrapper { public MyObjectWrapper(Version version) { super(version); } @Override protected TemplateModel handleUnknownType(Object obj) throws TemplateModelException { if (obj instanceof MySpecialType) { return new MySpecialTypeModel((MySpecialType) obj, this); } return super.handleUnknownType(obj); } } ``` -------------------------------- ### Define Macros and Functions in FreeMarker Template Source: https://context7.com/apache/freemarker/llms.txt Use macros for reusable UI components and functions for reusable logic within your FreeMarker templates. Import macros from other files using the `<#import>` directive. ```ftl <#-- Define a macro for card layout --> <#macro card title footer="">
${title}
<#nested>
<#if footer?has_content>
<#-- Define a function to format currency --> <#function formatCurrency amount currency="USD"> <#switch currency> <#case "USD"> <#return "$" + amount?string("0.00")> <#case "EUR"> <#return amount?string("0.00") + " EUR"> <#default> <#return amount?string("0.00") + " " + currency> <#-- Usage --> <@card title="Product Details" footer="Updated: ${.now?string('yyyy-MM-dd')}">

Product: ${product.name}

Price: ${formatCurrency(product.price)}

Price (EUR): ${formatCurrency(product.priceEur, "EUR")}

<#-- Include other templates --> <#include "header.ftlh"> <#include "partials/navigation.ftlh"> <#-- Import macros from another file --> <#import "lib/forms.ftl" as forms> <@forms.textInput name="email" label="Email Address" /> ``` -------------------------------- ### Load and Process FreeMarker Template Source: https://context7.com/apache/freemarker/llms.txt Load a template using the Configuration object and process it with a data model. Templates are automatically cached. Output can be directed to a Writer or a String. ```java import freemarker.template.*; import java.io.*; import java.util.*; // Assume cfg is your Configuration singleton Configuration cfg = getConfiguration(); // Create data model (a Map or Java bean) Map dataModel = new HashMap<>(); dataModel.put("user", "John Doe"); dataModel.put("message", "Welcome to FreeMarker!"); // Add a list List> products = new ArrayList<>(); products.add(Map.of("name", "Apple", "price", 1.99)); products.add(Map.of("name", "Banana", "price", 0.79)); products.add(Map.of("name", "Orange", "price", 2.49)); dataModel.put("products", products); // Load template (cached after first load) Template template = cfg.getTemplate("welcome.ftlh"); // Process template to output try (Writer out = new OutputStreamWriter(System.out)) { template.process(dataModel, out); } // Or process to string StringWriter stringWriter = new StringWriter(); template.process(dataModel, stringWriter); String result = stringWriter.toString(); // Output (given welcome.ftlh below): //

Welcome, John Doe!

//

Welcome to FreeMarker!

//
    //
  • Apple - $1.99
  • //
  • Banana - $0.79
  • //
  • Orange - $2.49
  • //
``` -------------------------------- ### Number Formatting Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins1.txt Shows various number formats, including negative numbers, decimals, and integers. Demonstrates how FreeMarker handles numeric literals. ```ftl number: -122,35 1500 5 0 0 true true true true true ``` -------------------------------- ### Iterator to List Mode Transition in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins-regexps-matches.txt Illustrates how iterator mode can transition to list mode, showing items with a count. ```ftl [L16]/4[L27]/4[L38]/4[L49]/4 [L16][L27][L38][L49] ``` -------------------------------- ### Zero Item Hash Test Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/hashliteral.txt Illustrates the creation and output of an empty hash. ```ftl <#assign test23 = {}> ${test23} ``` -------------------------------- ### Comparison Operators in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/comparisons.txt Illustrates various comparison operators in FreeMarker, including less than (<), less than or equal to (<=), greater than (>), and greater than or equal to (>=). These operators are used to evaluate conditions. ```ftl Item is: 0 Item is less than five. Item is less than or equals to seven. Item is: 1 Item is less than five. Item is less than or equals to seven. Item is: 2 Item is less than five. Item is less than or equals to seven. Item is: 3 Item is less than five. Item is less than or equals to seven. Item is greater than two. Item is: 4 Item is less than five. Item is less than or equals to seven. Item is greater than two. Item is: 5 Item is less than or equals to seven. Item is greater than two. Item is: 6 Item is less than or equals to seven. Item is greater than two. Item is: 7 Item is less than or equals to seven. Item is greater than two. Item is: 8 Item is greater than two. Item is: 9 Item is greater than two. Item is: 10 Item is greater than two. Item is greater than or equal to ten. Item is: 11 Item is greater than two. Item is greater than or equal to ten. Item is: 12 Item is greater than two. Item is greater than or equal to ten. ``` -------------------------------- ### Control Template Processing Environment in Java Source: https://context7.com/apache/freemarker/llms.txt Manually create and configure the processing environment for advanced control over locale, time zone, number formats, and variable settings. ```java import freemarker.template.*; import freemarker.core.Environment; import java.io.*; import java.util.*; // Create processing environment manually for more control Configuration cfg = getConfiguration(); Template template = cfg.getTemplate("report.ftlh"); Map dataModel = new HashMap<>(); dataModel.put("reportTitle", "Quarterly Sales"); StringWriter out = new StringWriter(); Environment env = template.createProcessingEnvironment(dataModel, out); // Configure environment settings before processing env.setLocale(Locale.GERMANY); env.setTimeZone(TimeZone.getTimeZone("Europe/Berlin")); env.setNumberFormat("#,##0.00"); env.setDateFormat("dd.MM.yyyy"); // Add variables directly to environment env.setVariable("generatedAt", env.getObjectWrapper().wrap(new Date())); // Process the template env.process(); String result = out.toString(); // Access current environment from within custom directives/methods: // Environment currentEnv = Environment.getCurrentEnvironment(); ``` -------------------------------- ### Test Simple Tag Loading from ClasspathTlds Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-javax-servlet/src/test/resources/freemarker/ext/jsp/webapps/tldDiscovery/WEB-INF/expected/test-noClasspath.txt This snippet indicates the successful execution of simple tags when loaded from ClasspathTlds. ```Java Executed TestSimpleTag2 Executed TestSimpleTag3 ``` -------------------------------- ### Simple Variable Assignment in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/hashconcat.txt Demonstrates basic variable assignment within a FreeMarker macro or template. Variables are assigned values using the '=' operator. ```ftl a = 1 b = 2 c = 3 X = 4 --- 1 2 3 4 ``` ```ftl d = 10 e = 20 f = 30 X = 40 --- 10 20 30 40 ``` -------------------------------- ### Generate FreeMarker API Documentation Source: https://github.com/apache/freemarker/blob/2.3-gae/README.md Generates the Javadoc for the FreeMarker API. The output is typically uploaded to the 'docs/api' directory of the website. ```bash ./gradlew javadoc ``` -------------------------------- ### Capitalize Each Word in String Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins1.txt Converts the first letter of each word in a string to uppercase. Apply this for title-casing text. ```ftl capitalize: Diebugsdie! * Vazzze 123456 --cdc-- --<<--@ X ${"kigyo"?upper_case} ``` -------------------------------- ### Simple String Output Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/macros.txt A basic FreeMarker template that outputs a static string. This is often used for simple text generation or as a base for more complex templates. ```ftl Hello World! Today is Monday. ``` -------------------------------- ### List with Else (Multiple Items) Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/list2.txt Renders each item on a new line when there are multiple items. The 'Empty!' text is not shown as the list is not empty. ```ftl aardvark bear cat dog ``` -------------------------------- ### String Interpolation and Escaping Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/string-builtins1.txt Demonstrates string interpolation and how special characters are handled and escaped within strings, including Unicode and control characters. ```ftl [a] = [a] [a\'x'\nb] = [a\'x'\nb] [\u0001\u001a ] = [\u0001\u001a ] ``` ```ftl [a] = [a] [a\\'x\'\nb] = [a\\'x\'\nb] [\x01\x1A ] = [\x01\x1A ] [\x3C![CDATA[] = [\x3C![CDATA[] []]\x3E] = []]\x3E] ``` ```ftl [a] = [a] [a\'x'\nb] = [a\'x'\nb] [\u0001\u001A ] = [\u0001\u001A ] [\n\r\t\f\b\"] = [\n\r\t\f\b\"] [\/]= [\/] [a/b] = [a/b] [<\/script>] = [<\/script>] [\u003C![CDATA[] = [\u003C![CDATA[] []]\u003E] = []]\u003E] ``` -------------------------------- ### List with Items, Separator, and Else (Multiple Items) Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/list2.txt Renders a comma-separated list within brackets. The 'Empty!' text is not shown as the list is not empty. ```ftl [ aardvark, bear, cat, dog ] ``` -------------------------------- ### Hash Reassignment with List Test Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/hashliteral.txt Shows reassigning a hash with a list and repeating the output. Observe how the list elements are accessed. ```ftl <#assign test23 = {"a": "Hello, world!", "list": ["Temporary", "Temporary", "Temporary"]}> ${test23.a} <#list test23.list as item> ${item} ${test23.c!1} ``` -------------------------------- ### Test Simple Tag Execution with Multiple Iterations Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-javax-servlet/src/test/resources/freemarker/ext/jsp/webapps/basic/WEB-INF/expected/customTags1.txt This test case demonstrates the execution of simple tags with multiple iterations. It shows how FreeMarker processes tags like 'simpletag1' and 'simpletag2', including their bodies and exit conditions. ```java enter TestSimpleTag simpletag1 invoking body i=0 foo enter TestSimpleTag simpletag2 invoking body i=0 bar invoking body i=1 bar invoking body i=2 bar exit TestSimpleTag simpletag2 invoking body i=1 foo enter TestSimpleTag simpletag2 invoking body i=0 bar invoking body i=1 bar invoking body i=2 bar exit TestSimpleTag simpletag2 exit TestSimpleTag simpletag1 ``` -------------------------------- ### Expected Native Image Output Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-test-graalvm-native/README.md This is the expected output when running the FreeMarker GraalVM native executable. It shows FreeMarker version and a simple HTML output generated by a template. ```txt INFO: name : FreeMarker Native Demo, version : 2.3.35-nightly Jan 15, 2025 4:28:19 PM freemarker.log._JULLoggerFactory$JULLogger info INFO: result : Hello : FreeMarker GraalVM Native Demo

Hello : FreeMarker GraalVM Native Demo

Test template for Apache FreeMarker GraalVM native support (2.3.35-nightly)

``` -------------------------------- ### Numeric List with Items (Multiple Items) Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/list2.txt Renders numbers enclosed in square brackets, with each number on a new line. ```ftl [ 11 22 33 ] ``` -------------------------------- ### Implement Custom Template Method (TemplateMethodModelEx) Source: https://context7.com/apache/freemarker/llms.txt Create custom functions callable from templates by implementing TemplateMethodModelEx. These functions receive arguments as TemplateModel objects. Ensure arguments are of the expected type to avoid runtime errors. ```java import freemarker.template.*; import java.util.List; // Custom method to calculate total price public class CalculateTotalMethod implements TemplateMethodModelEx { @Override public Object exec(List arguments) throws TemplateModelException { if (arguments.isEmpty()) { throw new TemplateModelException("calculateTotal requires a list argument"); } TemplateModel arg = (TemplateModel) arguments.get(0); if (!(arg instanceof TemplateSequenceModel)) { throw new TemplateModelException("Argument must be a sequence"); } TemplateSequenceModel products = (TemplateSequenceModel) arg; double total = 0; for (int i = 0; i < products.size(); i++) { TemplateHashModel product = (TemplateHashModel) products.get(i); TemplateNumberModel price = (TemplateNumberModel) product.get("price"); if (price != null) { total += price.getAsNumber().doubleValue(); } } return total; } } // Register with configuration cfg.setSharedVariable("calculateTotal", new CalculateTotalMethod()); // Usage in template: //

Total: $${calculateTotal(products)?string("0.00")}

// Output: Total: $5.27 ``` -------------------------------- ### Java Collections in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-javax-servlet/src/test/resources/freemarker/ext/jsp/webapps/basic/WEB-INF/expected/attributes-2.3.0.txt Shows how different Java collection types are interpreted and represented when used within a FreeMarker template context. Note that 'MyMap' is ignored. ```ftl Values created in Java: LinkedList: [1, 2, 3] [freemarker.template.SimpleSequence] ArrayList: [1, 2, 3] [freemarker.template.SimpleSequence] MyList: [1, 2, 3] [freemarker.template.SimpleSequence] LinkedHashMap: {a=1, b=2, c=3} [freemarker.template.SimpleHash] TreeMap: {a=1, b=2, c=3} [freemarker.template.SimpleHash] MyMap: [IGNORED] [freemarker.template.SimpleHash] TreeSet: [1, 2, 3] [freemarker.template.SimpleSequence] ``` -------------------------------- ### Numeric List with Items, Separator, and Else (Multiple Items) Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/list2.txt Renders a comma-separated list of numbers within brackets. The 'Empty!' text is not shown. ```ftl [ 11, 22, 33 ] ``` -------------------------------- ### XML Processing with Namespaces and CDATA Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/xml.txt Illustrates how to handle XML elements with namespaces and CDATA sections in FreeMarker. Pay attention to how CDATA content is preserved, including special characters. ```ftl text1text2 ``` ```ftl text1 ``` -------------------------------- ### Assigning Variables and Using Macros in FreeMarker Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/include.txt Assigns values to variables and defines a macro for repeated content inclusion. This snippet demonstrates basic variable assignment and macro definition within a FreeMarker template. ```ftl <#assign foo="assigning from included template", bar=" Can you see me? "> <#macro twice><#nested/>${bar}<#nested/> <#include "nestedinclude.ftl"> ``` -------------------------------- ### Hash Concatenation Test Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/hashliteral.txt Shows how to concatenate two hashes to create a new hash with combined key-value pairs. ```ftl <#assign hash1 = { "a": 1, "b": 2 }> <#assign hash2 = { "b": 3, "c": 4 }> <#assign combined = hash1 + hash2> <#list combined?keys as k> ${k} => ${combined[k]} ``` -------------------------------- ### List with Separator (Multiple Items) Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/list2.txt Renders a comma-separated list when there are multiple items. Use this for simple list outputs. ```ftl aardvark, bear, cat, dog ``` -------------------------------- ### Numeric List with Else (Multiple Items) Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/list2.txt Renders each number on a new line when there are multiple items. The 'Empty!' text is not shown. ```ftl 11 22 33 ``` -------------------------------- ### Catch-All Macro Parameter Test Source: https://github.com/apache/freemarker/blob/2.3-gae/freemarker-jython25/src/test/resources/freemarker/test/templatesuite/expected/macros.txt Tests the behavior of a macro with a catch-all parameter. This allows the macro to accept a variable number of arguments, which are then collected into a list. ```ftl foo=a baz=[] foo=a baz=[bar=b] foo=a baz=[bar=b, baz=c] ``` -------------------------------- ### FreeMarker Template Language (FTL) Basics Source: https://context7.com/apache/freemarker/llms.txt Basic FTL syntax for interpolations, directives, conditionals, loops, default values, null-safe access, and built-in functions. The .ftlh extension enables HTML auto-escaping. ```ftl <#-- welcome.ftlh - Template with auto-escaping -->

Welcome, ${user}!

${message}

<#-- Conditional logic --> <#if products?has_content>
    <#-- List iteration --> <#list products as product>
  • ${product.name} - $${product.price}
<#else>

No products available.

<#-- Default values for missing variables -->

Email: ${email!"Not provided"}

<#-- Null-safe access -->

City: ${user.address.city!"Unknown"}

<#-- Built-in functions -->

Total products: ${products?size}

User uppercase: ${user?upper_case}

Today: ${.now?string("yyyy-MM-dd")}

```