Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
La plantilla HTML es un archivo HTML estándar que contiene expresiones en línea especiales, indicadas por llaves dobles, que asignan la fuente de datos de entrada al marcado de la página HTML. Durante el procesamiento de la plantilla, estas expresiones en línea se reemplazarán con los valores de datos correspondientes según lo especificado por las reglas descritas en el artículo Plantilla HTML.
La biblioteca Aspose.HTML for .NET le permite establecer atributos en la plantilla HTML y controlar la presencia de atributos al completar las plantillas. El siguiente artículo le muestra cómo utilizar esta característica en ejemplos de C#.
Los atributos se utilizan para que los elementos HTML proporcionen información adicional sobre un elemento, especifiquen sus características o establezcan propiedades como id, clase, estilo, etc. Estos atributos se especifican en la etiqueta de apertura de un elemento HTML y se pueden configurar usando valores estáticos o datos dinámicos (expresiones en línea):
checked para la casilla de verificación HTMLPor ejemplo, tomemos la siguiente plantilla HTML:
1<input type="checkbox" {{attr}} disabled />Es un elemento de formulario de casilla de verificación que tiene un conjunto de atributos deshabilitado que lo hace no editable y una etiqueta {{attr}} a la que se le puede agregar un atributo basado en la fuente de datos. En esta etiqueta, utilizando la siguiente fuente de datos, estableceremos el atributo checked que mostrará una marca de verificación en esta casilla HTML cuando se dibuje:
1<Data><attr>checked</attr></Data>Un ejemplo completo de C# sobre cómo completar la plantilla se ve así:
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}Echemos un vistazo más de cerca a este fragmento de código C#:
content, baseUrl, data, options) para convertir la plantilla. Este método toma cuatro parámetros y convierte una cadena de contenido HTML en un objeto htmlDocument completamente formado:content (htmlCode): una cadena con código HTML para usar como plantilla;baseUrl (string.Empty): una cadena vacía en este ejemplo porque este parámetro no se utiliza;data (TemplateData): la fuente de datos para completar la plantilla. En este caso, es una cadena XML almacenada en la variable dataSource;options (TemplateLoadOptions): opciones de carga para la plantilla. Puedes crearlo usando el constructor
TemplateLoadOptions().<input> dentro del documento y verificamos que tenga los atributos correctos, como por ejemplo checked en este caso:<input>.<input>. La primera afirmación, Assert.True(input.Checked), verifica si la casilla de verificación está marcada. Las siguientes dos afirmaciones, Assert.Equal(3, input.Attributes.Length) y Assert.Equal("type", input.Attributes[0].Name), verifican el número de atributos y el nombre del primer atributo del elemento de entrada, respectivamente, y así sucesivamente.Save(path). El documento HTML se guarda en el archivo out-checked.html. El contenido de este archivo se puede ver a continuación:1<html>
2 <head>
3 </head>
4 <body>
5 <input type="checkbox" disabled="" checked="">
6 </body>
7</html>Si desea crear un documento basado en esta plantilla con un elemento de casilla de verificación vacío, utilice la siguiente fuente de datos:
1<Data><attr></attr></Data>Como puede ver, para obtener ese resultado, basta con pasar un valor vacío. El ejemplo de conversión completo se ve así:
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 ofrece Convertidores en línea gratuitos para convertir archivos HTML, XHTML, MHTML, EPUB, XML y Markdown a una variedad de formatos populares. Puede convertir fácilmente HTML a PDF, HTML a imagen, EPUB a PDF, SVG a PDF, MHTML a PDF, o MD a HTML. Simplemente seleccione un archivo, elija el formato a convertir y listo. ¡Prueba nuestros potentes convertidores gratis ahora!
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.