Created
March 6, 2013 16:44
-
-
Save aviatrix/5100780 to your computer and use it in GitHub Desktop.
This class removes Razor code blocks
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 static class ViewParser | |
{ | |
/// <summary> | |
/// This removes clode blocs in razor @{ //codegoes here } | |
/// </summary> | |
/// <param name="text">a view in a string format</param> | |
/// <returns>Parsed View</returns> | |
public static string RemoveCodeBlocks(string text) | |
{ | |
string rext = null; | |
var openBrackets = 0; | |
var openingIndex = 0; | |
//checking if we are already in a code block to remove | |
// this is very usefull especially if there are N codeblocks nested inside each other | |
bool isInBlock = false; | |
for (int j = 0; j < text.Length; j++) | |
{ | |
//finding the beginig of a code block | |
if (text[j] == '@' && text[j + 1] == '{') | |
{ | |
if (!isInBlock) | |
{ | |
isInBlock = true; | |
openingIndex = j; | |
} | |
} | |
// finding other opening brackets in the code block | |
if (text[j] == '{') | |
{ | |
openBrackets++; | |
} | |
if (text[j] == '}' && openBrackets != 0) | |
{ | |
openBrackets--; | |
// and finaly finding the closing bracjet | |
if (openBrackets == 0 && isInBlock) | |
{ | |
rext = text.Remove(openingIndex, (j - openingIndex) + 1); | |
openingIndex = 0; | |
RemoveCodeBlocks(rext); | |
//seticng this to false so it is marked as exited from the block | |
//and can continue to search for other code blocks | |
isInBlock = false; | |
return rext; | |
} | |
} | |
} | |
if (string.IsNullOrWhiteSpace(rext)) | |
{ | |
return text; | |
} | |
else | |
{ | |
return rext; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment