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:

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

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>

You can download the complete examples and data files from GitHub.

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:

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

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 “Banner Free Online Converters”

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.