Last active
December 13, 2015 21:59
-
-
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 …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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