Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include HTML document in .NET application with variable fields?

I have a C#/.NET app which currently uses StringBuilder to generate an HTML email message.

A new message format has been developed and now includes more formatting and CSS. I'd like to avoid appending each line of the file using StringBuilder, so I thought it best to include the HTML file as a resource.

However, there are about 21 variables within the CSS and HTML which I need to change on the fly. My first thought was to replace them with the standard String.Format placeholders ({0}, {1} etc) but when viewing the HTML, validation complains about these.

I'm rather stumped as to what the best practice is for storing a 200-line HTML file and changing parts of it before inclusion in an email.

Example:

Within the CSS, I need to change the color of certain elements, like this:

#header
{
    background-color: {0};
}

And within the HTML, I need to change strings and URLs, like this:

<img src="{1}" />
<span>{2}</span>

It seems including the HTML as a resource in the project would be best, but trying to use String.Format with that resource, regardless if it would work, is a poor method because of the aforementioned validation errors.

Any suggestions?

like image 292
JYelton Avatar asked May 18 '12 17:05

JYelton


3 Answers

I think you can try t4 tamplate

With t4 template you can even do more complex things like

<table>
<# for (int i = 1; i <= 10; i++)
   { #>
     <tr><td>Test name <#= i #> </td>
         <td>Test value <#= i * i #> </td> </tr>
 <# } #>
</table>
like image 127
Asif Mushtaq Avatar answered Oct 23 '22 22:10

Asif Mushtaq


You can use the Razor engine to render a HTML string:

<h2>Items:</h2>
@foreach(var item in list)
{
    <p>Item: @item.Description</p>
}

These answers Is it possible to use Razor View Engine outside asp.net give some nice links to do so.

like image 3
Lucas Reis Avatar answered Oct 24 '22 00:10

Lucas Reis


Instead of using {1} use a name e.g. Table1HeaderImage, then instead of using String.Format use String.Replace. You could have a collection of thingies to put in thehtml then, a quick loop, even extra attributes for customisation from users version, etc.

like image 2
Tony Hopkinson Avatar answered Oct 23 '22 23:10

Tony Hopkinson