Skip to content

Filling a template with information.

Jamie Brunton

Asked Oct 11, 2010, 10:39 AM EDT2 answers
Share
LinkedInX
I have been given a project from my manager which has got me kind of confused. I am relatively new to C# so bear with me.

We have a template provided to us that was used in a program that is now out of use, it has a nice html document with all of the values to be marked like %name% and %cost%. Now I would guess I could just open the file and search for those variables, the previous program however dealt with multiple variables. There are several %name% in there and %lesson% has several entries.

What I would like to know is - Is there an easy way to go manage the replacement of the holders?

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    Hi Jamie,
    Your guess is correct . You need to change/replace %name% and %cost% with your variables.
    You can use Find & Replace to change the %name% and %cost% to your variables.
     
    0
  • Mike Gold
    0
    Hi Jamie,
    The simplest thing you could do is just to do string replace of the HTML
    e.g.
    // 1) read HTML with StreamReader into a string (ReadToEnd) method
    //  2)   Replace the template values.  e.g.   myFileString = myFileString.Replace("%cost%", val).  Remember that strings are immutable so you need to assign after the replace
    // 3)  I would create a Dictionary of all the items you can replace ,  e.g. %name%,  val1    %lesson%, val2, etc.
    // 4) loop through the dictionary keys and find and replace them in the strng.
    If the template is more involved than this, for example, you are using arrays, then you might consider a more sophisticated template engine such as NVelocity or T4.
     
    0