Setting Attributes in HTML Template – C# Examples

HTML Template

The HTML template is a standard HTML file that contains special inline expressions, indicated by double curly brackets, which map the input data source to the HTML page markup. During template processing, these inline expressions will be replaced with the corresponding data values as specified by the rules outlined in the HTML Template article.

Aspose.HTML for .NET library allows you to set attributes in HTML template and control the presence of attributes when populating templates. The following article shows you how to use this feature in C# examples.

Set Attribute in HTML Template

Attributes are used for HTML elements to provide additional information about an element, specify its characteristics or set properties such as id, class, style, etc. These attributes are specified in the opening tag of an HTML element and can be set using static values or dynamic data (inline expressions):

Set Attribute checked for HTML Checkbox

For example, let’s take the following HTML template:

1<input type="checkbox" {{attr}} disabled />

It’s a checkbox form element that has a disabled attribute set which makes it uneditable and a {{attr}} label that can be added an attribute based on the data source. In this label, using the following data source, we will set the attribute checked which will display a checkmark in this HTML checkbox when drawn:

1<Data><attr>checked</attr></Data>

A complete C# example of filling the template looks like this:

 1// Bind XML data to HTML template and export as HTML and PNG using C#
 2
 3// Create a template with a string of HTML code
 4string htmlCode = "<input type=\"checkbox\" disabled {{attr}} />";
 5
 6// Set data for the template in XML format
 7string dataSource = "<Data><attr>checked</attr></Data>";
 8
 9// Convert template to HTML
10using (HTMLDocument htmlDocument = Converter.ConvertTemplate(htmlCode, string.Empty,
11           new TemplateData(new TemplateContentOptions(dataSource, TemplateContent.XML)),
12           new TemplateLoadOptions()))
13{
14    // Request the input checkbox element that we specified in the template
15    HTMLInputElement input = (HTMLInputElement)htmlDocument.GetElementsByTagName("input").First();
16
17    // Check if it has a checkmark 
18    Console.WriteLine("Checked: " + input.Checked);
19    Console.WriteLine("Attributes.Length: " + input.Attributes.Length);
20    Console.WriteLine("Attributes[0].Name: " + input.Attributes[0].Name);
21    Console.WriteLine("Attributes[1].Name: " + input.Attributes[1].Name);
22    Console.WriteLine("Attributes[2].Name: " + input.Attributes[2].Name);
23
24    /*
25    This example produces the following results:
26
27    Checked: True
28    Attributes.Length: 3
29    Attributes[0].Name: type
30    Attributes[1].Name: disabled
31    Attributes[2].Name: checked
32    */
33
34    // Save the HTML document to a file
35    htmlDocument.Save(Path.Combine(OutputDir, "out-checked.html"));
36
37    // Prepare a path to the output image file
38    string outputPath = Path.Combine(OutputDir, "out-checked.png"); 
39    
40    // Convert HTML to PNG using RenderTo() method
41    htmlDocument.RenderTo(new ImageDevice(new ImageRenderingOptions(), outputPath));
42}
Example-FillHTMLTemplate hosted with ❤ by GitHub

Let’s take a closer look at this C# code snippet:

  1. In the example, we create an HTML template from scratch, i.e., from the code string. So, first, we prepare HTML code.
  2. We use the ConvertTemplate(content, baseUrl, data, options) method to convert the template. This method takes four parameters and converts an HTML content string into a fully-formed htmlDocument object:
    • content (htmlCode) – a string with HTML code to use as the template;
    • baseUrl (string.Empty) – an empty string in this example because this parameter is not used;
    • data (TemplateData) – the data source for populating the template. In this case, it is an XML string stored in the dataSource variable;
    • options (TemplateLoadOptions) – load options for the template. You can create it using the TemplateLoadOptions() constructor.
  3. After creating the HTML document, we access an <input> element within the document and verify that it has the correct attributes, such as checked in this case:
    • We use the GetElementsByTagName() method to retrieve the first <input> element.
    • Then, we execute several assertions to check the properties of the <input> element. The first assertion, Assert.True(input.Checked), checks if the checkbox is checked. The following two assertions, Assert.Equal(3, input.Attributes.Length) and Assert.Equal("type", input.Attributes[0].Name), check the number of attributes and the name of the first attribute of the input element, respectively, and so on.
  4. To render HTML document to an image file, we use the RenderTo() method.
  5. Finally, we call the Save(path) method. HTML document is saved to the out-checked.html file. The content of this file can be seen below:
1<html>
2    <head>
3    </head>
4    <body>
5        <input type="checkbox" disabled="" checked="">
6    </body>
7</html>

Empty Checkbox

If you want to create a document based on this template with an empty checkbox element, then use the following data source:

1<Data><attr></attr></Data>

As you can see, to get such a result, it is enough to pass an empty value simply. The complete conversion example looks like this:

 1// Populate HTML template with XML data using attribute control in C#
 2
 3// Create a template with a string of HTML code
 4string htmlCode = "<input type=\"checkbox\" disabled {{attr}} />";
 5
 6// Create an empty data source that won't set an attribute
 7string dataSource = "<Data><attr></attr></Data>";
 8
 9// Convert template to HTML
10using (HTMLDocument htmlDocument = Converter.ConvertTemplate(htmlCode, string.Empty,
11           new TemplateData(new TemplateContentOptions(dataSource, TemplateContent.XML)),
12           new TemplateLoadOptions()))
13{
14    // Request the input checkbox element that we specified in the template
15    HTMLInputElement input = (HTMLInputElement)htmlDocument.GetElementsByTagName("input").First();
16
17    // Сheck if the checkbox is checked - it should not be there
18    Console.WriteLine("Checked: " + input.Checked);
19    Console.WriteLine("Attributes.Length: " + input.Attributes.Length);
20    Console.WriteLine("Attributes[0].Name: " + input.Attributes[0].Name);
21    Console.WriteLine("Attributes[1].Name: " + input.Attributes[1].Name);
22   
23    /*
24    This example produces the following results:
25
26    Checked: False
27    Attributes.Length: 2
28    Attributes[0].Name: type
29    Attributes[1].Name: disabled
30    */
31
32    // Save the HTML document to a file
33    htmlDocument.Save(Path.Combine(OutputDir, "out-unchecked.html"));
34
35    // Prepare a path to the output file
36    string outputPath = Path.Combine(OutputDir, "out-unchecked.png");
37
38    // Convert HTML to PNG
39    htmlDocument.RenderTo(new ImageDevice(new ImageRenderingOptions(), outputPath));
40}

Aspose.HTML offers free online Converters for converting HTML, XHTML, MHTML, EPUB, XML and Markdown files to a variety of popular formats. You can easily convert HTML to PDF, HTML to Image, EPUB to PDF, SVG to PDF, MHTML to PDF, or MD to HTML. Just select a file, choose the format to convert, and you’re done. Try our forceful Converters for free now!

Text “Free Online Converters”

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.