### JTE Task-Based Setup (Deprecated)
Source: https://github.com/casid/jte/blob/main/docs/gradle-plugin.md
This is an older, task-based setup for JTE compilation that is supported for backward compatibility but may be removed in future versions. The new approach uses the `jte` block.
```groovy
tasks.generateJte { // or precompileJte
sourceDirectory = Paths.get(project.projectDir.absolutePath, "src", "main", "jte")
contentType = ContentType.Html
}
```
--------------------------------
### Example Usage of jte Facade
Source: https://github.com/casid/jte/blob/main/docs/jte-models.md
Demonstrates how to instantiate and use the generated facade to render a template. Use StaticTemplates for production builds.
```java
OutputStream output = ...
Templates templates = new StaticTemplates();
templates.helloWorld("Hi!").render(output);
```
--------------------------------
### jte Template Example
Source: https://github.com/casid/jte/blob/main/docs/spring-boot-starter-2.md
A basic jte template that accepts a model and displays a text property.
```html
@import com.example.demo.DemoModel
@param DemoModel model
Hello ${model.text}!
```
--------------------------------
### Start DirectoryWatcher in Kotlin
Source: https://github.com/casid/jte/blob/main/docs/hot-reloading.md
Start the DirectoryWatcher daemon thread in Kotlin to listen for template file changes and re-render static HTML files when detected. Ensure this is only active in a development environment.
```kotlin
if (isDeveloperEnvironment()) {
val watcher = DirectoryWatcher(templateEngine, codeResolver)
watcher.start(templates -> templates.forEach { /* re-render the static HTML file */ });
}
```
--------------------------------
### Start DirectoryWatcher in Java
Source: https://github.com/casid/jte/blob/main/docs/hot-reloading.md
Start the DirectoryWatcher daemon thread in Java to listen for template file changes and re-render static HTML files when detected. Ensure this is only active in a development environment.
```java
if (isDeveloperEnvironment()) {
DirectoryWatcher watcher = new DirectoryWatcher(templateEngine, codeResolver);
watcher.start(templates -> {
for (String template : templates) {
// Re-render the static HTML file
}
});
}
```
--------------------------------
### Render with Utf8ByteOutput (Kotlin)
Source: https://github.com/casid/jte/blob/main/docs/binary-rendering.md
Example of rendering a template using Utf8ByteOutput and writing the content to an HttpServletResponse in Kotlin. This output is optimized for binary templates.
```kotlin
val output = Utf8ByteOutput()
templateEngine.render(template, page, output)
response.contentLength = output.contentLength
response.contentType = "text/html"
response.characterEncoding = "UTF-8"
response.status = page.statusCode
response.outputStream.use { os ->
output.writeTo(os)
}
```
--------------------------------
### Render with Utf8ByteOutput (Java)
Source: https://github.com/casid/jte/blob/main/docs/binary-rendering.md
Example of rendering a template using Utf8ByteOutput and writing the content to an HttpServletResponse. This output is optimized for binary templates.
```java
Utf8ByteOutput output = new Utf8ByteOutput();
templateEngine.render(template, page, output);
response.setContentLength(output.getContentLength());
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.setStatus(page.getStatusCode());
try (OutputStream os = response.getOutputStream()) {
output.writeTo(os);
}
```
--------------------------------
### JSP to JTE Converter Setup
Source: https://github.com/casid/jte/blob/main/docs/jsp-converter.md
Extend JspToJteConverter and implement the main method to initiate the conversion process. Configure formatting, imports, custom tag converters, inlined includes, and suppressions.
```java
import gg.jte.convert.jsp.Converter;
import gg.jte.convert.jsp.JspElementType;
import gg.jte.convert.jsp.JspToJteConverter;
import java.nio.file.Path;
import java.util.EnumSet;
public class JspConverter extends JspToJteConverter {
// The IntelliJ plugin will look for the main method of a class extending JspToJteConverter, when you click Code/Convert JSP file to jte file
public static void main( String[] args ) {
convertFromIntelliJPlugin(args, new JspConverter(), JspConverter::init);
}
public static void init(Converter converter ) {
// Configure, how your jte files should be formatted
converter.setIndentationCount(3);
converter.setIndentationChar(' ');
converter.setLineSeparator("\n");
// Configure default imports for your jte files
converter.setPrefix("@import static my.JteContext.*\n");
// Register converters for your custom JSP tags
converter.register("my:tag1", new MyTag1Converter());
converter.register("my:tag2", new MyTag2Converter());
// If you have a global import file that you include in every JSP, you need to define it here
String imports = "/WEB-INF/jsp/includes/import.jsp";
converter.addInlinedInclude(imports);
// Configure all JSP elements that the converter should ignore.
converter.addSuppressions(
imports,
EnumSet.of(JspElementType.UseBean, JspElementType.Scriptlet, JspElementType.Comment, JspElementType.CustomTag, JspElementType.Declaration)
);
}
public JspConverter() {
super(
Path.of("webapp/WEB-INF"), // Your WEB-INF directory, containing JSPs
Path.of("webapp/jte"), // Your jte root directory
"my:jte" // The name of your jte bridging tag (more details below)
);
}
}
```
--------------------------------
### Configure jte-maven-plugin with ModelExtension
Source: https://github.com/casid/jte/blob/main/docs/maven-plugin.md
Configure the jte-maven-plugin to use the ModelExtension for generating code. This example shows how to specify source directories, content types, and extension settings like annotations, language, and include/exclude patterns.
```xml
gg.jte
jte-maven-plugin
${jte.version}
${project.basedir}/src/main/jte
Html
gg.jte.models.generator.ModelExtension
@foo.bar.MyAnnotation
@foo.bar.MyAnnotation
Java
\.pages\..*
\.components\..*
generate-sources
generate
```
--------------------------------
### Define Nullable Parameter in .kte
Source: https://github.com/casid/jte/blob/main/docs/kotlin.md
Example of defining a nullable String parameter in a .kte template. This allows the parameter to accept null values.
```html
@param name: String?
```
--------------------------------
### Model Class Definitions for Data Display
Source: https://github.com/casid/jte/blob/main/docs/syntax.md
Example model classes in Java and Kotlin that can be used with JTE templates to display data. These classes define the properties that can be accessed via ${}.
```java
package my;
public class Model {
public String name = "jte";
}
```
```kotlin
package my
data class Model(val name: String = "jte")
```
--------------------------------
### Define Non-null Parameter in .kte
Source: https://github.com/casid/jte/blob/main/docs/kotlin.md
Example of defining a non-null String parameter in a .kte template. Ensure parameters match their expected nullability to avoid runtime errors.
```html
@param name: String
```
--------------------------------
### Spring WebMVC Controller Example
Source: https://github.com/casid/jte/blob/main/docs/spring-boot-starter-2.md
A Spring WebMVC controller that adds a model attribute and returns a view name, which the jte ViewResolver will process.
```java
@GetMapping("/")
public String view(Model model, HttpServletResponse response) {
model.addAttribute("model", new DemoModel("Hello World"));
return "demo";
}
```
--------------------------------
### Define Content Block in Java
Source: https://github.com/casid/jte/blob/main/docs/index.md
Use the `@param Content content` to define a content block that can be provided by callers. `${content}` renders this block. This example refactors a template to use a layout with a content parameter.
```html
@import org.example.Page
@param Page page
@template.layout(page = page, content = @`
Welcome to my example page!
`)
```
--------------------------------
### Render Template (Java)
Source: https://github.com/casid/jte/blob/main/docs/index.md
Renders a JTE template with provided data and outputs the result to a StringOutput. This is a common way to get template content as a string.
```java
import gg.jte.TemplateOutput;
import gg.jte.output.StringOutput;
...
TemplateOutput output = new StringOutput();
templateEngine.render("example.jte", page, output);
System.out.println(output);
```
--------------------------------
### JSP Bridging Tag Example
Source: https://github.com/casid/jte/blob/main/docs/jsp-converter.md
This JSP code demonstrates how to use a bridging tag to embed JTE templates within JSP. It specifies the JTE template to render and passes parameters.
```jsp
```
--------------------------------
### Initialize Template Engine (Java)
Source: https://github.com/casid/jte/blob/main/docs/index.md
Sets up the JTE TemplateEngine by specifying the directory for template files and the content type. Ensure the 'jte' directory exists.
```java
import gg.jte.CodeResolver;
import gg.jte.TemplateEngine;
import gg.jte.resolve.DirectoryCodeResolver;
...
CodeResolver codeResolver = new DirectoryCodeResolver(Path.of("jte")); // This is the directory where your .jte files are located.
TemplateEngine templateEngine = TemplateEngine.create(codeResolver, ContentType.Html); // Two choices: Plain or Html
```
--------------------------------
### Create Precompiled Template Engine with Directory
Source: https://github.com/casid/jte/blob/main/docs/pre-compiling.md
Initialize the `TemplateEngine` using precompiled templates located in a specified directory. This is the recommended approach for production environments.
```java
Path targetDirectory = Path.of("jte-classes"); // This is the directory where compiled templates are located.
TemplateEngine templateEngine = TemplateEngine.createPrecompiled(targetDirectory, ContentType.Html);
```
--------------------------------
### Basic Hello World Template
Source: https://github.com/casid/jte/blob/main/docs/syntax.md
A minimal JTE template that outputs static text. Rendering this template will produce the exact text content.
```html
Hello world!
```
--------------------------------
### Initialize Template Engine (Kotlin)
Source: https://github.com/casid/jte/blob/main/docs/index.md
Sets up the JTE TemplateEngine for Kotlin by specifying the directory for template files and the content type. Ensure the 'kte' directory exists.
```kotlin
import gg.jte.CodeResolver
import gg.jte.TemplateEngine
import gg.jte.resolve.DirectoryCodeResolver
...
val codeResolver = DirectoryCodeResolver(Path.of("kte")) // This is the directory where your .kte files are located.
val templateEngine = TemplateEngine.create(codeResolver, ContentType.Html) // Two choices: Plain or Html
```
--------------------------------
### Add jte Spring Boot 3 Starter Dependencies (Maven)
Source: https://github.com/casid/jte/blob/main/docs/spring-boot-starter-3.md
Include these dependencies in your Maven project to use the jte Spring Boot 3 starter and the jte library.
```xml
gg.jte
jte-spring-boot-starter-3
{{ latest-git-tag }}
gg.jte
jte
{{ latest-git-tag }}
```
--------------------------------
### Add jte Spring Boot 2 Starter Dependencies
Source: https://github.com/casid/jte/blob/main/docs/spring-boot-starter-2.md
Include these dependencies in your Maven or Gradle build to use the jte Spring Boot 2 starter.
```xml
gg.jte
jte-spring-boot-starter-2
{{ latest-git-tag }}
gg.jte
jte
{{ latest-git-tag }}
```
```groovy
implementation "gg.jte:jte-spring-boot-starter-2:{{ latest-git-tag }}"
implementation "gg.jte:jte:{{ latest-git-tag }}"
```
--------------------------------
### Add jte Spring Boot 3 Starter Dependencies (Gradle)
Source: https://github.com/casid/jte/blob/main/docs/spring-boot-starter-3.md
Add these dependencies to your Gradle project to enable the jte Spring Boot 3 starter and the jte library.
```groovy
implementation "gg.jte:jte-spring-boot-starter-3:{{ latest-git-tag }}"
implementation "gg.jte:jte:{{ latest-git-tag }}"
```
--------------------------------
### Layout Template with Content Placeholder (Kotlin)
Source: https://github.com/casid/jte/blob/main/docs/index.md
Defines a reusable layout template in Kotlin that accepts content to be rendered within its structure. Use this for shared page elements.
```html
@import org.example.Page
@import gg.jte.Content
@param page: Page
@param content: Content
@if(page.description != null)
@endif
${page.title}
${page.title}
${content}
```
--------------------------------
### jte Configuration Properties
Source: https://github.com/casid/jte/blob/main/docs/spring-boot-starter-2.md
Configure the production profile name and template location using these properties.
```properties
gg.jte.productionProfileName=k8s
gg.jte.templateLocation=src/main/templates
```
--------------------------------
### Initialize precompiled template engine for production
Source: https://github.com/casid/jte/blob/main/docs/pre-compiling.md
Initialize the jte TemplateEngine using precompiled templates for production builds. This loads templates directly from the application class loader.
```java
TemplateEngine templateEngine = TemplateEngine.createPrecompiled(ContentType.Html);
```
--------------------------------
### Create jte TemplateEngine instance
Source: https://github.com/casid/jte/blob/main/docs/rendering-a-template.md
Create a TemplateEngine instance once per application. It is thread-safe and can be shared. Specify the directory containing your .jte files and the content type.
```java
import gg.jte.ContentType;
import gg.jte.TemplateEngine;
import gg.jte.CodeResolver;
import gg.jte.resolve.DirectoryCodeResolver;
// ...
CodeResolver codeResolver = new DirectoryCodeResolver(Path.of("jte")); // This is the directory where your .jte files are located.
TemplateEngine templateEngine = TemplateEngine.create(codeResolver, ContentType.Html);
```
```kotlin
import gg.jte.ContentType
import gg.jte.TemplateEngine
import gg.jte.CodeResolver
import gg.jte.resolve.DirectoryCodeResolver
// ...
val codeResolver = DirectoryCodeResolver(Path.of("jte")) // This is the directory where your .jte files are located.
val templateEngine = TemplateEngine.create(codeResolver, ContentType.Html)
```
--------------------------------
### Looping with ForSupport in JTE (Java)
Source: https://github.com/casid/jte/blob/main/docs/syntax.md
Leverage ForSupport to access loop metadata like index and iteration status within Java JTE templates. Import `gg.jte.support.ForSupport` to use its methods.
```html
@import gg.jte.support.ForSupport
<%-- ... --%>
@for(var entryLoop : ForSupport.of(model.entries))
${entryLoop.get().title}
@endfor
```
--------------------------------
### Basic JTE Template Structure (Kotlin)
Source: https://github.com/casid/jte/blob/main/docs/index.md
Defines a simple HTML template with imports, parameters, and conditional logic for Kotlin projects. Use this for basic page structures.
```html
@import org.example.Page
@param page: Page
@if(page.description != null)
@endif
${page.title}
${page.title}
Welcome to my example page!
```
--------------------------------
### Define a Layout Template with Content Blocks
Source: https://github.com/casid/jte/blob/main/docs/syntax.md
Defines a layout template that accepts `gg.jte.Content` objects for dynamic content and footers. This allows for flexible content injection, similar to Java lambdas.
```jte
@import org.example.Page
@import gg.jte.Content
@param Page page
@param Content content
@param Content footer = null
@if(page.getDescription() != null)
@endif
${page.getTitle()}
${page.getTitle()}
${content}
@if (footer != null)
@endif
```
--------------------------------
### Add jte Spring Boot 4 Starter Core Dependency (Maven)
Source: https://github.com/casid/jte/blob/main/docs/spring-boot-starter-4.md
Use this Maven dependency if you only need the jte TemplateEngine auto-configuration without the ViewResolver.
```xml
gg.jte
jte-spring-boot-starter-4-core
{{ latest-git-tag }}
```
--------------------------------
### Enable Binary Encoding in Maven
Source: https://github.com/casid/jte/blob/main/docs/pre-compiling.md
Configure the jte-maven-plugin to use binary static content. Additionally, use the maven-resources-plugin to copy the generated .bin files to the output directory, as the jte plugin does not handle this automatically.
```xml
jte-maven-plugin
true
...
maven-resources-plugin
process-classes
copy-resources
${project.build.outputDirectory}
${project.basedir}/target/generated-sources/jte
**/*.bin
false
```
--------------------------------
### Enable Binary Encoding in Gradle
Source: https://github.com/casid/jte/blob/main/docs/pre-compiling.md
Configure the jte extension in your Gradle build file to enable binary static content for precompiled templates.
```groovy
jte {
binaryStaticContent = true
}
```
--------------------------------
### Precompile jte templates with Gradle (Groovy)
Source: https://github.com/casid/jte/blob/main/docs/pre-compiling.md
Configure the Gradle build to precompile all jte templates. Ensure the jte Gradle plugin version matches the jte dependency version.
```groovy
plugins {
id 'java'
id 'gg.jte.gradle' version '${jte.version}'
}
dependencies {
implementation('gg.jte:jte:${jte.version}')
}
jte {
precompile()
}
```
--------------------------------
### Configure jte Template Location and Suffix
Source: https://github.com/casid/jte/blob/main/docs/spring-boot-starter-4.md
Customize the directory where jte templates are located and their file extension using application properties.
```properties
gg.jte.templateLocation=src/main/jte
gg.jte.templateSuffix=.jte
```
--------------------------------
### Call a Layout Template with Content Blocks
Source: https://github.com/casid/jte/blob/main/docs/syntax.md
Calls a layout template, passing dynamic content and footer sections using the shorthand `@`` syntax for `gg.jte.Content`.
```jte
@import org.example.WelcomePage
@param WelcomePage welcomePage
@template.layout.page(
page = welcomePage,
content = @`
Welcome, ${welcomePage.getUserName()}.
`,
footer = @`
Thanks for visiting, come again soon!
`
)
```
--------------------------------
### Configure jte Maven Plugin precompile goal
Source: https://github.com/casid/jte/blob/main/docs/maven-plugin.md
Configure the jte-maven-plugin to precompile templates. Specify source and target directories, and content type. This goal runs during the process-classes phase.
```xml
gg.jte
jte-maven-plugin
${jte.version}
${project.basedir}/src/main/jte
${project.build.directory}/jte-classes
Html
process-classes
precompile
```
--------------------------------
### Custom HTML Template Output in Kotlin
Source: https://github.com/casid/jte/blob/main/docs/html-rendering.md
Provide a custom implementation of HtmlTemplateOutput by extending OwaspHtmlTemplateOutput or creating your own. Wrap your actual TemplateOutput before rendering.
```kotlin
val output = MySecureHtmlOutput(StringOutput())
```
--------------------------------
### Precompile jte templates with Gradle (Kotlin)
Source: https://github.com/casid/jte/blob/main/docs/pre-compiling.md
Configure the Kotlin DSL for Gradle to precompile all jte templates. Ensure the jte Gradle plugin version matches the jte dependency version.
```kotlin
plugins {
java
id("gg.jte.gradle") version("${jte.version}")
}
dependencies {
implementation("gg.jte:jte:${jte.version}")
}
jte {
precompile()
}
```
--------------------------------
### Basic JTE Template Structure (Java)
Source: https://github.com/casid/jte/blob/main/docs/index.md
Defines a simple HTML template with imports, parameters, and conditional logic. Use this for basic page structures.
```html
@import org.example.Page
@param Page page
@if(page.getDescription() != null)
@endif
${page.getTitle()}
${page.getTitle()}
Welcome to my example page!
```
--------------------------------
### Enable Binary Static Content (Application Run Time)
Source: https://github.com/casid/jte/blob/main/docs/binary-rendering.md
Enable binary static content encoding at application run time. This setting is available since jte 1.7.0.
```java
templateEngine.setBinaryStaticContent(true);
```
```kotlin
templateEngine.binaryStaticContent = true
```
--------------------------------
### Add jte Spring Boot 4 Starter Dependency (Maven)
Source: https://github.com/casid/jte/blob/main/docs/spring-boot-starter-4.md
Include this dependency in your Maven project to use the jte Spring Boot 4 Starter.
```xml
gg.jte
jte-spring-boot-starter-4
{{ latest-git-tag }}
```
--------------------------------
### Configure Precompile Task in Kotlin
Source: https://github.com/casid/jte/blob/main/docs/gradle-plugin.md
Use this snippet to configure the `precompileJte` task in a Kotlin build script. It applies the jte plugin and sets up the necessary dependencies.
```kotlin
plugins {
java
id("gg.jte.gradle") version("${jteVersion}")
}
dependencies {
implementation("gg.jte:jte:${jteVersion}")
}
jte {
precompile()
}
```
--------------------------------
### Layout Template with Content Placeholder (Java)
Source: https://github.com/casid/jte/blob/main/docs/index.md
Defines a reusable layout template that accepts content to be rendered within its structure. Use this for shared page elements.
```html
@import org.example.Page
@import gg.jte.Content
@param Page page
@param Content content
@if(page.getDescription() != null)
@endif
${page.getTitle()}
${page.getTitle()}
${content}
```
--------------------------------
### Enable jte Development Mode
Source: https://github.com/casid/jte/blob/main/docs/spring-boot-starter-4.md
Set developmentMode to true to enable the jte file watcher for hot-reloading templates. This requires a JDK.
```properties
gg.jte.developmentMode=true
```
--------------------------------
### Custom HTML Template Output in Java
Source: https://github.com/casid/jte/blob/main/docs/html-rendering.md
Provide a custom implementation of HtmlTemplateOutput by extending OwaspHtmlTemplateOutput or creating your own. Wrap your actual TemplateOutput before rendering.
```java
TemplateOutput output = new MySecureHtmlOutput(new StringOutput());
```
--------------------------------
### Create self-contained JAR with precompiled templates (Kotlin)
Source: https://github.com/casid/jte/blob/main/docs/pre-compiling.md
Configure the Kotlin DSL for Gradle JAR task to include precompiled template classes and binary files. This is useful for building self-contained JARs.
```kotlin
tasks.jar {
dependsOn(tasks.precompileJte)
from(fileTree("jte-classes") {
include("**/*.class")
include("**/*.bin") // Only required if you use binary templates
})
}
```
--------------------------------
### Call a Template with Varargs
Source: https://github.com/casid/jte/blob/main/docs/syntax.md
Calls a template that uses varargs, passing multiple string elements as individual arguments after the named parameters.
```jte
@template.list(title = "Things to do", "Cook dinner", "Eat", "Netflix and Chill")
```
--------------------------------
### Define a Template with Default Parameter Values
Source: https://github.com/casid/jte/blob/main/docs/syntax.md
Defines a template with default values for parameters. Parameters with default values only need to be explicitly passed if a non-default value is required.
```jte
@import my.Entry
@param Entry entry
@param boolean verbose = false
${entry.title}
@if(verbose)
${entry.subtitle}
@endif
```
--------------------------------
### Configure jte to Use Precompiled Templates
Source: https://github.com/casid/jte/blob/main/docs/spring-boot-starter-4.md
Set usePrecompiledTemplates to true for production use with a JRE, requiring precompilation via Maven/Gradle plugin.
```properties
gg.jte.usePrecompiledTemplates=true
```
--------------------------------
### Implement JTE LocalizationSupport in Java
Source: https://github.com/casid/jte/blob/main/docs/localization.md
Implement the `gg.jte.support.LocalizationSupport` interface to bridge JTE with your existing localization framework. This class handles the lookup of localized strings.
```java
public class JteLocalizer implements gg.jte.support.LocalizationSupport {
private final OtherFrameworkLocalizer frameworkLocalizer;
private final Locale locale;
public JteLocalizer(OtherFrameworkLocalizer frameworkLocalizer, Locale locale) {
this.frameworkLocalizer = frameworkLocalizer;
this.locale = locale;
}
@Override
public String lookup(String key) {
// However this works in your localization framework
return frameworkLocalizer.get(locale, key);
}
}
```
--------------------------------
### Configure Precompile Task in Groovy
Source: https://github.com/casid/jte/blob/main/docs/gradle-plugin.md
Use this snippet to configure the `precompileJte` task in a Groovy build script. It applies the jte plugin and sets up the necessary dependencies.
```groovy
plugins {
id 'java'
id 'gg.jte.gradle' version '${jteVersion}'
}
dependencies {
implementation('gg.jte:jte:${jteVersion}')
}
jte {
precompile()
}
```
--------------------------------
### Configure JTE Maven Plugin for Native Image Resources
Source: https://github.com/casid/jte/blob/main/docs/maven-plugin.md
Configure the jte-maven-plugin to use the NativeResourcesExtension for native image builds. Specify the source directory and content type.
```xml
gg.jte
jte-maven-plugin
${jte.version}
${project.basedir}/src/main/jte
Html
gg.jte.nativeimage.NativeResourcesExtension
generate-sources
generate
```
--------------------------------
### Generate jte templates with Gradle (Groovy)
Source: https://github.com/casid/jte/blob/main/docs/pre-compiling.md
Configure the Gradle build to generate all jte templates. Ensure the jte Gradle plugin version matches the jte dependency version.
```groovy
plugins {
id 'java'
id 'gg.jte.gradle' version '${jte.version}'
}
dependencies {
implementation('gg.jte:jte:${jte.version}')
}
jte {
generate()
}
```
--------------------------------
### Configure JTE Model Generation (Groovy DSL)
Source: https://github.com/casid/jte/blob/main/docs/gradle-plugin.md
Use this snippet to configure the JTE Gradle plugin for generating models. Specify target language, annotations, and include/exclude patterns for templates.
```groovy
plugins {
id 'gg.jte.gradle' version '${jte.version}'
}
dependencies {
implementation 'gg.jte:jte-runtime:${jte.version}'
jteGenerate 'gg.jte:jte-models:${jte.version}'
}
jte {
generate()
// Remove the properties that don't make sense to your project
jteExtension('gg.jte.models.generator.ModelExtension') {
// Target language ("Java" and "Kotlin" are supported). "Java" is the default.
language = 'Java'
// Annotations to add to generated interfaces and classes
interfaceAnnotation = '@foo.bar.MyAnnotation'
implementationAnnotation = '@foo.bar.MyAnnotation'
// Patterns to include (or exclude) certain templates
includePattern = '\.pages\..*'
excludePattern = '\.components\..*'
}
}
```
--------------------------------
### Render a jte template
Source: https://github.com/casid/jte/blob/main/docs/rendering-a-template.md
Render a template by providing its name, a model containing data, and a TemplateOutput implementation. The model can be any class, or a Map if multiple parameters are needed.
```java
import gg.jte.TemplateOutput;
import gg.jte.output.StringOutput;
// ...
TemplateOutput output = new StringOutput();
templateEngine.render("example.jte", model, output);
```
```kotlin
import gg.jte.TemplateOutput
import gg.jte.output.StringOutput
// ...
val output = StringOutput()
templateEngine.render("example.jte", model, output)
```
--------------------------------
### Configure JTE Native Resources (Kotlin DSL)
Source: https://github.com/casid/jte/blob/main/docs/gradle-plugin.md
Configure the JTE Gradle plugin to generate necessary configuration files for GraalVM native-image using Kotlin DSL. This extension is available since jte 1.10.0.
```kotlin
plugins {
id("gg.jte.gradle") version "${jte.version}"
}
dependencies {
implementation("gg.jte:jte-runtime:${jte.version}")
jteGenerate("gg.jte:jte-models:${jte.version}")
}
jte {
generate()
jteExtension("gg.jte.nativeimage.NativeResourcesExtension")
}
```
--------------------------------
### Create self-contained JAR with precompiled templates (Groovy)
Source: https://github.com/casid/jte/blob/main/docs/pre-compiling.md
Configure the Gradle JAR task to include precompiled template classes and binary files. This is useful for building self-contained JARs.
```groovy
jar {
dependsOn precompileJte
from fileTree("jte-classes") {
include "**/*.class"
include "**/*.bin" // Only required if you use binary templates
}
}
```
--------------------------------
### Generate jte templates with Maven
Source: https://github.com/casid/jte/blob/main/docs/pre-compiling.md
Configure the Maven POM file to use the jte-maven-plugin to generate all jte templates during the 'generate-sources' phase. Ensure the plugin version matches the dependency version.
```xml
gg.jte
jte-maven-plugin
${jte.version}
${project.basedir}/src/main/jte
Html
generate-sources
generate
```
--------------------------------
### Configure jte-maven-plugin generate goal
Source: https://github.com/casid/jte/blob/main/docs/maven-plugin.md
Configure the jte-maven-plugin to run the 'generate' goal during the 'generate-sources' phase. Specify the source directory for JTE templates and the content type.
```xml
gg.jte
jte-maven-plugin
${jte.version}
${project.basedir}/src/main/jte
Html
generate-sources
generate
```
--------------------------------
### Generate jte templates with Gradle (Kotlin)
Source: https://github.com/casid/jte/blob/main/docs/pre-compiling.md
Configure the Kotlin DSL for Gradle to generate all jte templates. Ensure the jte Gradle plugin version matches the jte dependency version.
```kotlin
plugins {
java
id("gg.jte.gradle") version("${jte.version}")
}
dependencies {
implementation("gg.jte:jte:${jte.version}")
}
jte {
generate()
}
```
--------------------------------
### Configure JTE Native Resources (Groovy DSL)
Source: https://github.com/casid/jte/blob/main/docs/gradle-plugin.md
Configure the JTE Gradle plugin to generate necessary configuration files for GraalVM native-image. This extension is available since jte 1.10.0.
```groovy
plugins {
id 'gg.jte.gradle' version '${jte.version}'
}
dependencies {
implementation 'gg.jte:jte-runtime:${jte.version}'
jteGenerate 'gg.jte:jte-models:${jte.version}'
}
jte {
generate()
jteExtension('gg.jte.nativeimage.NativeResourcesExtension')
}
```
--------------------------------
### Call a Template in a Subdirectory
Source: https://github.com/casid/jte/blob/main/docs/syntax.md
Calls a template located in a subdirectory, similar to package structure in Java. The path reflects the directory structure relative to the jte root.
```jte
@template.my.entry.drawEntry(model.entry1, true)
@template.my.entry.drawEntry(model.entry2, false)
```
--------------------------------
### Gradle Groovy DSL Configuration for jte-models
Source: https://github.com/casid/jte/blob/main/docs/jte-models.md
Set up the jte-gradle-plugin in your Groovy DSL build script, specifying the ModelExtension and adding jte-models as a generation dependency.
```groovy
plugins {
id 'gg.jte.gradle' version '${jte.version}'
}
dependencies {
implementation 'gg.jte:jte-runtime:${jte.version}'
jteGenerate 'gg.jte:jte-models:${jte.version}'
}
jte {
generate()
binaryStaticContent = true
jteExtension 'gg.jte.models.generator.ModelExtension'
}
```
--------------------------------
### Configure Maven Compiler Source and Target
Source: https://github.com/casid/jte/blob/main/docs/maven-plugin.md
Alternatively, configure Maven compiler source and target properties to set default compile arguments for JTE templates.
```xml
21
21
```
--------------------------------
### Gradle Kotlin DSL Configuration for jte-models
Source: https://github.com/casid/jte/blob/main/docs/jte-models.md
Configure the jte-gradle-plugin using Kotlin DSL, including the ModelExtension and declaring jte-models for code generation.
```kotlin
plugins {
id("gg.jte.gradle") version "${jte.version}"
}
dependencies {
implementation("gg.jte:jte-runtime:${jte.version}")
jteGenerate("gg.jte:jte-models:${jte.version}")
}
jte {
generate()
binaryStaticContent.set(true)
jteExtension("gg.jte.models.generator.ModelExtension")
}
```
--------------------------------
### Looping with ForSupport in JTE (Kotlin)
Source: https://github.com/casid/jte/blob/main/docs/syntax.md
Use ForSupport for loop details such as index and iteration status in Kotlin JTE templates. Ensure `gg.jte.support.ForSupport` is imported.
```html
@import gg.jte.support.ForSupport
<%-- ... --%>
@for(entryLoop in ForSupport.of(model.entries))
${entryLoop.get().title}
@endfor
```
--------------------------------
### Configure JTE Model Generation (Kotlin DSL)
Source: https://github.com/casid/jte/blob/main/docs/gradle-plugin.md
Use this snippet to configure the JTE Gradle plugin for generating models in Kotlin DSL. Specify target language, annotations, and include/exclude patterns for templates.
```kotlin
plugins {
id("gg.jte.gradle") version "${jte.version}"
}
dependencies {
implementation("gg.jte:jte-runtime:${jte.version}")
jteGenerate("gg.jte:jte-models:${jte.version}")
}
jte {
generate()
// Remove the properties that don't make sense to your project
jteExtension("gg.jte.models.generator.ModelExtension") {
// Target language ("Java" and "Kotlin" are supported). "Java" is the default.
property("language", "Java")
// Annotations to add to generated interfaces and classes
property("interfaceAnnotation", "@foo.bar.MyAnnotation")
property("implementationAnnotation", "@foo.bar.MyAnnotation")
// Patterns to include (or exclude) certain templates
property("includePattern", "\.pages\..*")
property("excludePattern", '\.components\..*')
}
}
```
--------------------------------
### Call a Template with Positional Parameters
Source: https://github.com/casid/jte/blob/main/docs/syntax.md
Calls another template using positional arguments. The order of arguments must match the parameter order defined in the called template.
```jte
@template.my.drawEntry(model.entry1, true)
@template.my.drawEntry(model.entry2, false)
```
--------------------------------
### Conditional Template Engine Creation
Source: https://github.com/casid/jte/blob/main/docs/pre-compiling.md
Instantiate the template engine differently based on whether the environment is for development (with hot reloading) or production (with precompiled templates).
```java
if (isDeveloperMachine()) {
// create template engine with hot reloading (a bit slower)
} else {
// create template engine with precompiled templates (fastest)
}
```
--------------------------------
### Add jte Spring Boot 4 Starter Dependency (Gradle)
Source: https://github.com/casid/jte/blob/main/docs/spring-boot-starter-4.md
Add this dependency to your Gradle project for jte Spring Boot 4 Starter integration.
```groovy
implementation "gg.jte:jte-spring-boot-starter-4:{{ latest-git-tag }}"
```
--------------------------------
### Call a Template with Default Parameters Omitted
Source: https://github.com/casid/jte/blob/main/docs/syntax.md
Demonstrates calling a template where a parameter with a default value is omitted. The default value will be used in this case.
```jte
@template.my.entry.drawEntry(entry = model.entry1, verbose = true)
@template.my.entry.drawEntry(entry = model.entry2)
```
--------------------------------
### Render Template (Kotlin)
Source: https://github.com/casid/jte/blob/main/docs/index.md
Renders a JTE template with provided data and outputs the result to a StringOutput in Kotlin. This is useful for obtaining template content as a string.
```kotlin
import gg.jte.TemplateOutput
import gg.jte.output.StringOutput
...
val output = StringOutput()
templateEngine.render("example.kte", page, output)
println(output)
```
--------------------------------
### Define a Template with Varargs
Source: https://github.com/casid/jte/blob/main/docs/syntax.md
Defines a template that accepts a variable number of arguments for its last parameter. This is useful for creating flexible list or collection-based components.
```jte
@param String title
@param String ... elements
${title}
@for(var element : elements)
- ${element}
@endfor
```
--------------------------------
### Maven Plugin for Precompiling JTE Templates
Source: https://github.com/casid/jte/blob/main/docs/pre-compiling.md
Configure the jte-maven-plugin in your `pom.xml` to precompile JTE templates during the Maven build process. Ensure the `sourceDirectory` and `targetDirectory` match your project structure and the runtime configuration.
```xml
gg.jte
jte-maven-plugin
${jte.version}
${project.basedir}/src/main/jte
${project.build.directory}/jte-classes
Html
process-classes
precompile
```
--------------------------------
### Call a Template with Named Parameters
Source: https://github.com/casid/jte/blob/main/docs/syntax.md
Calls a template using named parameters, which improves readability and removes dependency on parameter order. This is the default suggestion by the IntelliJ plugin.
```jte
@template.my.entry.drawEntry(entry = model.entry1, verbose = true)
@template.my.entry.drawEntry(entry = model.entry2, verbose = false)
```
--------------------------------
### Render Page with ThreadLocal Localizer in Java
Source: https://github.com/casid/jte/blob/main/docs/localization.md
Initialize and dispose of the `JteLocalizer` using `ThreadLocal` within a `try-finally` block before rendering a JTE template. This ensures the context is properly managed for each request.
```java
public void renderPage(String template, Locale locale) {
try {
JteContext.init(new JteLocalizer(this.frameworkLocalizer, locale));
templateEngine.render(template);
} finally {
JteContext.dispose();
}
}
```
--------------------------------
### Add jte Spring Boot 4 Starter Core Dependency (Gradle)
Source: https://github.com/casid/jte/blob/main/docs/spring-boot-starter-4.md
Add this Gradle dependency for jte TemplateEngine auto-configuration, excluding the ViewResolver.
```groovy
implementation "gg.jte:jte-spring-boot-starter-4-core:{{ latest-git-tag }}"
```
--------------------------------
### Define Content Block in Kotlin
Source: https://github.com/casid/jte/blob/main/docs/index.md
Similar to Java, Kotlin uses `@param` for content blocks. The syntax for defining the content block with `@` and backticks remains consistent.
```html
@import org.example.Page
@param page: Page
@template.layout(page = page, content = @`
Welcome to my example page!
`)
```
--------------------------------
### Add jte Dependency for Gradle
Source: https://github.com/casid/jte/blob/main/docs/index.md
Add this line to your build.gradle file to include jte in your Gradle project.
```groovy
implementation("{{ POM_GROUP_ID }}:jte:{{ latest-git-tag }}")
```
--------------------------------
### Generated Kotlin Facade Interface
Source: https://github.com/casid/jte/blob/main/docs/jte-models.md
The Kotlin equivalent of the generated facade interface. Each method maps to a jte template and returns a JteModel for rendering.
```kotlin
interface Templates {
fun helloWord(greeting: String): JteModel
}
```
--------------------------------
### Render Page with ThreadLocal Localizer in Kotlin
Source: https://github.com/casid/jte/blob/main/docs/localization.md
Manage the `JteLocalizer` initialization and disposal using `ThreadLocal` within a `try-finally` block before rendering a JTE template. This guarantees correct context management for each request.
```kotlin
fun renderPage(template: String, locale: Locale) {
try {
JteContext.init(JteLocalizer(this.frameworkLocalizer, locale))
templateEngine.render(template)
} finally {
JteContext.dispose()
}
}
```
--------------------------------
### Use Static Localize Method in JTE Template
Source: https://github.com/casid/jte/blob/main/docs/localization.md
Import and use static `localize` methods from `JteContext` for a concise way to access localized strings directly within your JTE templates, simplifying template code.
```html
@import static my.JteContext.*
${localize("my.title")}
${localize("my.greetings", user.getName())}
```
--------------------------------
### Define a Reusable Template
Source: https://github.com/casid/jte/blob/main/docs/syntax.md
Defines a template with parameters that can be reused across other templates. Ensure all templates are located within the jte root directory.
```jte
@import my.Entry
@param Entry entry
@param boolean verbose
${entry.title}
@if(verbose)
${entry.subtitle}
@endif
```
--------------------------------
### Maven Configuration for jte-models
Source: https://github.com/casid/jte/blob/main/docs/jte-models.md
Configure the jte-maven-plugin to include the ModelExtension for generating typesafe facades. Ensure the jte-models artifact is included as a dependency.
```xml
gg.jte
jte-maven-plugin
${jte.version}
${project.basedir}/src/main/jte
Html
gg.jte.models.generator.ModelExtension
generate-sources
generate
gg.jte
jte-models
${jte.version}
```
--------------------------------
### Handle Nullable Lists in @for Loop
Source: https://github.com/casid/jte/blob/main/docs/kotlin.md
Safely iterate over a potentially null list in a .kte template by providing an empty list as a default. This prevents errors when the list is null.
```html
@for(things in (things ?: listOf()))
```
--------------------------------
### Implement JTE LocalizationSupport in Kotlin
Source: https://github.com/casid/jte/blob/main/docs/localization.md
Implement the `gg.jte.support.LocalizationSupport` interface in Kotlin to integrate JTE with your existing localization framework. This class manages the retrieval of localized strings.
```kotlin
class JteLocalizer(frameworkLocalizer: OtherFrameworkLocalizer, locale: Locale) : gg.jte.support.LocalizationSupport {
override fun lookup(String key): String {
// However this works in your localization framework
return frameworkLocalizer.get(locale, key)
}
}
```
--------------------------------
### Maven Dependency for jte Watcher
Source: https://github.com/casid/jte/blob/main/docs/hot-reloading.md
Add the jte-watcher module as a Maven dependency to enable hot reloading for statically rendered websites.
```xml
gg.jte
jte-watcher
${jte.version}
```
--------------------------------
### Add jte Dependency for Maven
Source: https://github.com/casid/jte/blob/main/docs/index.md
Include this dependency in your pom.xml to use jte in your Maven project.
```xml
{{ POM_GROUP_ID }}
jte
{{ latest-git-tag }}
```
--------------------------------
### Displaying Data in JTE Templates
Source: https://github.com/casid/jte/blob/main/docs/syntax.md
Use ${} to display data from a model within JTE templates. Ensure the model properties are accessible and of supported types; unsupported types will cause compilation errors.
```html
@import my.Model
@param Model model
Hello ${model.name}!
```
```html
@import my.Model
@param model: Model
Hello ${model.name}!
```
--------------------------------
### Configure Maven Compiler Release
Source: https://github.com/casid/jte/blob/main/docs/maven-plugin.md
Set the Maven compiler release property to configure default compile arguments for JTE templates.
```xml
21
```
--------------------------------
### Gradle Dependency for jte Watcher
Source: https://github.com/casid/jte/blob/main/docs/hot-reloading.md
Add the jte-watcher module as a Gradle dependency to enable hot reloading for statically rendered websites.
```groovy
implementation("gg.jte:jte-watcher:${jteVersion}")
```
--------------------------------
### Register Additional JTE Generation Task
Source: https://github.com/casid/jte/blob/main/docs/gradle-plugin.md
Register a new `GenerateJteTask` for specific JTE templates with custom content type, source, and target directories. This task is then depended upon by the `compileJava` task and its output is added to the main Java source set.
```groovy
import gg.jte.ContentType
import gg.jte.gradle.GenerateJteTask
plugins {
id 'java'
id 'gg.jte.gradle' version '${jte.version}'
}
dependencies {
implementation('gg.jte:jte:${jte.version}')
}
def additionalGenerateTask = tasks.register("additionalGenerateTask", GenerateJteTask) {
contentType = ContentType.Plain
sourceDirectory = file("src/main/otherJte").toPath()
targetDirectory = file("build/additionalGenerateTask").toPath()
packageName = "gg.jte.additionalgeneratetask"
}
tasks.named("compileJava") {
dependsOn(additionalGenerateTask)
}
sourceSets.named("main") {
java.srcDir(additionalGenerateTask.map {it.targetDirectory})
}
```
--------------------------------
### Raw HTML Output with @raw Keyword
Source: https://github.com/casid/jte/blob/main/docs/html-rendering.md
Use the @raw keyword to include HTML sections that should not be processed by JTE. This is useful for embedding scripts or other raw HTML content.
```html
@raw
@endraw
```
--------------------------------
### Bypass Output Escaping with $unsafe{}
Source: https://github.com/casid/jte/blob/main/docs/html-rendering.md
Use $unsafe{} to render content without escaping, but be aware of potential XSS risks. This is useful when you trust the data being outputted, like a username.
```html
$unsafe{userName}
```
--------------------------------
### For Loops in JTE (Java)
Source: https://github.com/casid/jte/blob/main/docs/syntax.md
Iterate over collections using @for and @endfor in JTE templates. Supports standard Java for-each loops, enhanced for loops with 'var', and traditional for loops.
```html
@for(Entry entry : model.entries)
${entry.title}
@endfor
@for(var entry : model.entries)
${entry.title}
@endfor
@for(int i = 0; i < 10; ++i)
i is ${i}
@endfor
```