Generate HTML from Templates in Java

Use Converter.convertTemplate() to populate an HTML template with XML or JSON data. Define placeholders in the template, load the structured data with TemplateData, configure TemplateLoadOptions, and save or return the populated HTML document.

An HTML template is reusable markup containing placeholders for dynamic values. Aspose.HTML for Java matches template expressions with fields in an XML or JSON data source and substitutes the corresponding values. This workflow is useful for generated pages, reports, HTML email bodies, document fragments, and other server-side HTML generation tasks.

The convertTemplate() overloads accept an HTML template as a file path, URL, inline string, or HTMLDocument. Depending on the overload, the result is saved to an output path or returned as an HTMLDocument for further processing.

Understanding HTML Template Syntax

Template expressions use double curly braces to map values from the data source into the HTML markup. A field name can address a top-level value, while dot notation accesses nested values.

Data-Binding Expressions

A data-binding expression has the following form:

{{ data-binding expression }}

For example, the following XML data contains personal and address information.

XML data source

1<Data>
2<FirstName>John</FirstName>
3<LastName>Doe</LastName>
4<Address>
5    <City>Chicago</City>
6    <Street>Oakmound Drive</Street>
7    <Number>100</Number>
8</Address>
9</Data>

The HTML template uses {{FirstName}} and {{LastName}} for top-level values. Expressions such as {{Address.Street}} use dot notation to read nested values.

HTML template

 1<table border=1>
 2    <tr>
 3        <th>Person</th>
 4        <th>Address</th>
 5    </tr>
 6    <tr>
 7        <td>{{FirstName}} {{LastName}}</td>
 8        <td>{{Address.Street}} {{Address.Number}}, {{Address.City}}</td>
 9    </tr>
10</table>

Foreach Directive Expressions

Use a {{#foreach ... }} directive together with data-binding expressions to repeat markup for items in a collection. The next XML source contains several Person elements under Persons.

XML data source

 1<Data>
 2    <Persons>
 3        <Person>
 4                <FirstName>John</FirstName>
 5                <LastName>Doe</LastName>
 6                <Address>
 7                        <Number>100</Number>
 8                        <Street>Oakmound Drive</Street>
 9                        <City>Chicago</City>
10                </Address>
11                <Phone1>773-349-7747</Phone1>
12                <Phone2>708-252-9790</Phone2>
13        </Person>
14        <Person>
15                <FirstName>Jack</FirstName>
16                <LastName>Fox</LastName>
17                <Address>
18                        <Number>355</Number>
19                        <Street>Haul Road</Street>
20                        <City>San Francisco</City>
21                </Address>
22                <Phone1>650-942-7641</Phone1>
23            </Person>
24            <Person>
25                <FirstName>Sherlock</FirstName>
26                <LastName>Holmes</LastName>
27                <Address>
28                        <Number>45</Number>
29                        <Street>Baker str.</Street>
30                        <City>London</City>
31                </Address>
32                <Phone1>012-5146-564</Phone1>
33        </Person>
34    </Persons>
35</Data>

Assign the directive to the data_merge attribute. In this example, Persons.Person selects the repeated collection, and the expressions inside the table are evaluated for each Person item.

HTML template

 1<table border=1 data_merge='{{#foreach Persons.Person}}'>
 2    <tr>
 3        <th>Person</th>
 4        <th>Address</th>
 5    </tr>
 6    <tr>
 7        <td>{{FirstName}} {{LastName}}</td>
 8        <td>{{Address.Street}} {{Address.Number}}, {{Address.City}}</td>
 9    </tr>
10</table>

The current implementation supports the foreach directive on DIV, OL, UL, and TABLE elements.

XML and JSON Data Sources

Template data can be stored in XML or JSON. Keep the structure and field names aligned with the expressions used by the HTML template. The following XML and JSON examples represent the same values.

XML data source

1 <Data>
2    <FirstName>John</FirstName>
3    <LastName>Doe</LastName>
4    <Address>
5        <City>Chicago</City>
6        <Street>Oakmound Drive</Street>
7        <Number>100</Number>
8    </Address>
9</Data>

JSON data source

1{
2     "FirstName": "John",
3     "LastName": "Doe",
4     "Address": {
5         "City": "Chicago",
6         "Street": "Oakmound Drive",
7         "Number": "100"
8     }
9 }

Convert an HTML Template to HTML

Follow these steps to populate an HTML template programmatically:

  1. Prepare a valid XML or JSON data source.
  2. Prepare an HTML template containing data-binding or foreach expressions.
  3. Create a TemplateData object for the data source.
  4. Create TemplateLoadOptions and configure name matching if required.
  5. Call Converter.convertTemplate() with the template, data, options, and output destination.

The following example writes JSON data to data-source.json and reusable markup to template.html. It creates TemplateData and TemplateLoadOptions, then populates the template and saves the result as document.html.

 1// Populate an HTML template with structured JSON data using Java
 2
 3// Prepare a JSON data-source and save it to a file
 4String data =
 5        "{\n" +
 6                "   'FirstName': 'John',\n" +
 7                "   'LastName': 'Smith',\n" +
 8                "   'Address': {\n" +
 9                "       'City': 'Dallas',\n" +
10                "       'Street': 'Austin rd.',\n" +
11                "       'Number': '200'\n" +
12                "       }\n" +
13                "}";
14try (java.io.FileWriter fileWriter = new java.io.FileWriter("data-source.json")) {
15    fileWriter.write(data);
16}
17
18// Prepare an HTML Template and save it to a file
19String template =
20        "<table border=1>\n" +
21                "    <tr>\n" +
22                "        <th>Person</th>\n" +
23                "        <th>Address</th>\n" +
24                "    </tr>\n" +
25                "    <tr>\n" +
26                "        <td>{{FirstName}} {{LastName}}</td>\n" +
27                "        <td>{{Address.Street}} {{Address.Number}}, {{Address.City}}</td>\n" +
28                "    </tr>\n" +
29                "</table>\n";
30try (java.io.FileWriter fileWriter = new java.io.FileWriter("template.html")) {
31    fileWriter.write(template);
32}
33
34// Convert Template to HTML
35com.aspose.html.converters.Converter.convertTemplate(
36        "template.html",
37        new com.aspose.html.converters.TemplateData("data-source.json"),
38        new com.aspose.html.loading.TemplateLoadOptions(), "document.html"
39);

Download complete Java examples and data files from GitHub.

Control Case-Sensitive Name Matching

TemplateLoadOptions controls whether template expressions and data item names are matched with case sensitivity. The default value of NamesAreCaseSensitive is true.

Validate the XML or JSON before conversion and keep field paths consistent with the template expressions. Case-insensitive matching can accommodate inconsistent capitalization, but it does not correct missing fields or an incorrect data hierarchy.

Related Resources

Other Platforms