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

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

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.