Skip to content

Instantly share code, notes, and snippets.

@randyburden
Last active December 13, 2015 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save randyburden/4981687 to your computer and use it in GitHub Desktop.
Save randyburden/4981687 to your computer and use it in GitHub Desktop.
DoubleBracketedTokenHelper - A template / token helper thingy I put together where each token is wrapped in double brackets a la handlebars.js like. This is definately half-baked and is meant to be more of a "Hey, note to self: next time your coding a template helper, remember to look at this gist to get some ideas about how to go about writing …
public class DoubleBracketedTokenHelper
{
public Dictionary<string, string> TokensAndValues = new Dictionary<string, string>();
/// <summary>
/// Tokens to ignore.
/// </summary>
public List<string> IgnoredTokens = new List<string> { "{{cr}}" };
// This finds any characters in between open and closing double brackets
// As an example, the following string will match on the following results:
// String: On {{DayOfTheWeek}} I went to the store and spent {{Amount}}.
// Match 1: {{DayOfTheWeek}}
// Match 2: {{Amount}}
const string FindDoubleBracketedTokens = @"\{\{[^}]*\}\}";
public string DeTokenize( string stringWithTokens )
{
var matches = Regex.Matches( stringWithTokens, FindDoubleBracketedTokens, RegexOptions.Compiled );
foreach ( Match match in matches )
{
string token = match.Value;
if ( string.IsNullOrWhiteSpace( token ) || IgnoredTokens.Contains( token ) ) continue;
string key = GetTokenValue( token );
string value;
if ( TokensAndValues.TryGetValue( key, out value ) == false )
{
throw new Exception( string.Format( "There is no data to substitute for the following token: {0}", match ) );
}
stringWithTokens = stringWithTokens.Replace( token, value );
}
return stringWithTokens;
}
public virtual string GetTokenValue( string token )
{
if ( string.IsNullOrWhiteSpace( token ) ) return token;
return token.Replace( "{{", "" ).Replace( "}}", "" );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment