Last active
March 7, 2016 19:00
-
-
Save fresc81/42363f1d04b630745f6d to your computer and use it in GitHub Desktop.
templating using regexes and embedded VBScripts
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
'example: | |
''''''''' | |
'Set scope = New Dictionary | |
'scope.Add "anrede", "Herr" | |
'scope.Add "vorname", "Herbert" | |
'scope.Add "name", "Müller" | |
'Debug.Print ApplyTemplate("Sehr geehrte{{Wenn(anrede=""Herr"",""r"","""")}} {{anrede}} {{vorname}} {{name}},", scope) | |
' -> prints "Sehr geehrter Herr Herbert Müller," | |
Const SCRIPT_PATTERN As String = "{{([^}]*)}}" | |
' use VBScript to evaluate all {{KEY}} placeholders in the text and replace them with their result | |
Public Function ApplyTemplate(ByVal text As String, ByRef scope As Dictionary) As String | |
Dim regEx As New RegExp | |
Dim runtime As New ScriptControl | |
Dim key As String | |
Dim value As String | |
Dim found As Match | |
Dim matches As MatchCollection | |
Dim script As String | |
Dim result As String | |
Dim main As MSScriptControl.Module | |
Dim lhs As String | |
Dim rhs As String | |
' setup script runtime | |
With runtime | |
.Language = "VBScript" | |
.Reset | |
.AllowUI = False | |
.UseSafeSubset = True | |
End With | |
Set main = runtime.Modules.Add("Template") | |
main.AddCode "Public Function Wenn (cond, valueTrue, valueFalse)" & vbCrLf & _ | |
" If cond = True Then" & vbCrLf & _ | |
" Wenn = valueTrue" & vbCrLf & _ | |
" Else" & vbCrLf & _ | |
" Wenn = valueFalse" & vbCrLf & _ | |
" End If" & vbCrLf & _ | |
"End Function" & vbCrLf | |
' add all columns as variables into the scriptlet | |
ApplyTemplate = text | |
For i = 0 To scope.Count - 1 | |
key = scope.Keys(i) | |
value = scope.Items(i) | |
' set variable in script runtime | |
main.AddCode key & " = """ & value & """ " | |
Next i | |
With regEx | |
.Global = False | |
.IgnoreCase = False | |
.MultiLine = True | |
.Pattern = SCRIPT_PATTERN | |
End With | |
' for each found scriptlet... | |
Set matches = regEx.Execute(ApplyTemplate) | |
While matches.Count > 0 | |
' extract and evaluate embedded scriptlet | |
Set found = matches(0) | |
script = found.SubMatches(0) | |
result = CStr(main.Eval(script)) | |
lhs = Left(ApplyTemplate, found.FirstIndex) | |
rhs = Right(ApplyTemplate, Len(ApplyTemplate) - Len(lhs) - found.Length) | |
ApplyTemplate = lhs & result & rhs | |
Set matches = regEx.Execute(ApplyTemplate) | |
Wend | |
Set runtime = Nothing | |
Set regEx = Nothing | |
Set found = Nothing | |
Set matches = Nothing | |
Set main = Nothing | |
End Function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment