Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aspose-com-gists/de3b5ea762bd66d03c59a89e44829727 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/de3b5ea762bd66d03c59a89e44829727 to your computer and use it in GitHub Desktop.
Populate an HTML template from data sources, set attributes on templates, convert template to HTML

Working with HTML Template – Populate from XML or JSON data sources

This gist repository contains C# code examples from the Working with HTML Template chapter of the Aspose.HTML for .NET documentation. These gists demonstrate how to populate HTML templates with data, convert templates to standard HTML, and programmatically control template attributes when generating dynamic content.

Overview

HTML templates are a powerful way to create structured, reusable layouts that can be populated from data sources, for example, XML or JSON. Using Aspose.HTML for .NET, you can programmatically manipulate templates, insert content, and convert results into a variety of formats.

What You’ll Learn

  • Populate HTML templates with data from various sources.
  • Set attributes in HTML template and control the presence of attributes when populating with data.
  • Render and save the populated HTML template to formats like HTML, PDF, or images.

Examples Overview

Example Folder Description
Example-ConvertWithASingleLine Converts an HTML template to HTML using a single line of code, taking a template file and a JSON data source.
Example-ConvertTemplate Converts an HTML document from a source path using a specified XML template data file and saves the result to an output path.
Example-ConvertHTMLTemplateOnTheFly Demonstrates how to prepare a JSON data source and an HTML template string, save them to files, and then populate the template with the data.
Example-FillHTMLTemplate Shows how to create an HTML template with an input checkbox, set template data in XML format, convert the template to HTML, and then verify the checkbox's attributes and state.
Example-UncheckedTemplate Creates an HTML template with a disabled checkbox, uses an empty data source to ensure it's unchecked, and then verifies its state and attributes.

How to Use These Examples

  1. Install Aspose.HTML for .NET via NuGet.
  2. Configure paths, settings, and inputs to suit your environment.
  3. Browse the available gists and copy the code samples you need.
  4. Run your project to see the example in action.

You can download a free trial of Aspose.HTML for .NET and use a temporary license for unrestricted access.

Documentation

For a comprehensive understanding, context, and detailed explanations of each example, please refer to the official documentation chapter Working with HTML Template.

Additional Links

Prerequisites

  1. .NET 6 or later
  2. Aspose.HTML for .NET
Aspose.HTML for .NET – Working with HTML Templates
// Populate an HTML template with structured JSON data using C#
// Learn more: https://docs.aspose.com/html/net/convert-template-to-html/
// Prepare a path to JSON data source file
string jsonPath = Path.Combine(OutputDir, "data-source.json");
// Prepare a JSON data source and save it to the file
string data = @"{
""FirstName"": ""John"",
""LastName"": ""Doe"",
""Address"": {
""City"": ""Dallas"",
""Street"": ""Austin rd."",
""Number"": ""200""
}
}";
File.WriteAllText(jsonPath, data);
// Prepare a path to an HTML Template file
string sourcePath = Path.Combine(OutputDir, "template.html");
// Prepare an HTML Template and save it to the file
string template = @"
<table border=1>
<tr>
<th>Person</th>
<th>Address</th>
</tr>
<tr>
<td>{{FirstName}} {{LastName}}</td>
<td>{{Address.Street}} {{Address.Number}}, {{Address.City}}</td>
</tr>
</table>
";
File.WriteAllText(sourcePath, template);
// Prepare a path to the output file (data-filled template file)
string outputPath = Path.Combine(OutputDir, "template-output.html");
// Invoke Converter.ConvertTemplate() method in order to populate "template.html" with the data source from "data-source.json" file
Converter.ConvertTemplate(sourcePath, new TemplateData(jsonPath), new TemplateLoadOptions(), outputPath);
// Populate HTML template with external XML data using C#
// Learn more: https://docs.aspose.com/html/net/convert-template-to-html/
// Prepare a path to an HTML source file
string sourcePath = Path.Combine(DataDir, "template.html");
// Prepare a path to an xml template data file
string templateDataPath = Path.Combine(DataDir, "templateData.xml");
// Define TemplateData object instance
TemplateData templateData = new TemplateData(templateDataPath);
// Prepare a path to the result file
string resultPath = Path.Combine(OutputDir, "result.html");
// Define default TemplateLoadOptions object
TemplateLoadOptions options = new TemplateLoadOptions();
// Initialize an HTML document as conversion source
HTMLDocument document = new HTMLDocument(sourcePath, new Configuration());
// Convert template to HTML
Converter.ConvertTemplate(document, templateData, options, resultPath);
// Clear resources
document.Dispose();
// Convert Template to HTML using C#
// Learn more: https://docs.aspose.com/html/net/convert-template-to-html/
// Convert template to HTML
Converter.ConvertTemplate(
Path.Combine(DataDir, "template.html"),
new TemplateData(Path.Combine(DataDir, "data-source.json")),
new TemplateLoadOptions(),
Path.Combine(OutputDir, "template-with-single-line.html")
);
// Bind XML data to HTML template and export as HTML and PNG using C#
// Learn more: https://docs.aspose.com/html/net/setting-attributes-in-html-template/
// Create a template with a string of HTML code
string htmlCode = "<input type=\"checkbox\" disabled {{attr}} />";
// Set data for the template in XML format
string dataSource = "<Data><attr>checked</attr></Data>";
// Convert template to HTML
using (HTMLDocument htmlDocument = Converter.ConvertTemplate(htmlCode, string.Empty,
new TemplateData(new TemplateContentOptions(dataSource, TemplateContent.XML)),
new TemplateLoadOptions()))
{
// Request the input checkbox element that we specified in the template
HTMLInputElement input = (HTMLInputElement)htmlDocument.GetElementsByTagName("input").First();
// Check if it has a checkmark
Console.WriteLine("Checked: " + input.Checked);
Console.WriteLine("Attributes.Length: " + input.Attributes.Length);
Console.WriteLine("Attributes[0].Name: " + input.Attributes[0].Name);
Console.WriteLine("Attributes[1].Name: " + input.Attributes[1].Name);
Console.WriteLine("Attributes[2].Name: " + input.Attributes[2].Name);
/*
This example produces the following results:
Checked: True
Attributes.Length: 3
Attributes[0].Name: type
Attributes[1].Name: disabled
Attributes[2].Name: checked
*/
// Save the HTML document to a file
htmlDocument.Save(Path.Combine(OutputDir, "out-checked.html"));
// Prepare a path to the output image file
string outputPath = Path.Combine(OutputDir, "out-checked.png");
// Convert HTML to PNG using RenderTo() method
htmlDocument.RenderTo(new ImageDevice(new ImageRenderingOptions(), outputPath));
}
// Populate HTML template with XML data using attribute control in C#
// Learn more: https://docs.aspose.com/html/net/setting-attributes-in-html-template/
// Create a template with a string of HTML code
string htmlCode = "<input type=\"checkbox\" disabled {{attr}} />";
// Create an empty data source that won't set an attribute
string dataSource = "<Data><attr></attr></Data>";
// Convert template to HTML
using (HTMLDocument htmlDocument = Converter.ConvertTemplate(htmlCode, string.Empty,
new TemplateData(new TemplateContentOptions(dataSource, TemplateContent.XML)),
new TemplateLoadOptions()))
{
// Request the input checkbox element that we specified in the template
HTMLInputElement input = (HTMLInputElement)htmlDocument.GetElementsByTagName("input").First();
// Сheck if the checkbox is checked - it should not be there
Console.WriteLine("Checked: " + input.Checked);
Console.WriteLine("Attributes.Length: " + input.Attributes.Length);
Console.WriteLine("Attributes[0].Name: " + input.Attributes[0].Name);
Console.WriteLine("Attributes[1].Name: " + input.Attributes[1].Name);
/*
This example produces the following results:
Checked: False
Attributes.Length: 2
Attributes[0].Name: type
Attributes[1].Name: disabled
*/
// Save the HTML document to a file
htmlDocument.Save(Path.Combine(OutputDir, "out-unchecked.html"));
// Prepare a path to the output file
string outputPath = Path.Combine(OutputDir, "out-unchecked.png");
// Convert HTML to PNG
htmlDocument.RenderTo(new ImageDevice(new ImageRenderingOptions(), outputPath));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment