Last active
December 10, 2024 14:21
-
-
Save deanebarker/3865c8cc1fa156395f3e45b2090186f9 to your computer and use it in GitHub Desktop.
A hacked up way of writing script-ish code in Liquid/Fluid
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 usage | |
var data = new LiquidScriptData() | |
{ | |
["first_name"] = "Annie", | |
["last_name"] = "Barker" | |
}; | |
var keysThatChanged = data.Evaluate(@" | |
if first_name == 'Annie' | |
assign first_name = 'Deane' | |
endif | |
"); | |
// data["first_name"] now equals "Deane" | |
// keysThatChanged contains one value: "first_name" | |
public class LiquidScriptData : Dictionary<string, object> | |
{ | |
private static FluidParser _parser = new FluidParser(new FluidParserOptions { AllowFunctions = true }); | |
public IEnumerable<string> Evaluate(string script) | |
{ | |
var modifiedKeys = new List<string>(); | |
var source = @$" | |
{{% liquid | |
{script} | |
%}}"; | |
_parser.TryParse(source, out var template, out var error); | |
var context = new TemplateContext(); | |
foreach (var item in this) | |
{ | |
context.SetValue(item.Key, item.Value); | |
} | |
context.Assigned = (identifier, value, context) => | |
{ | |
this[identifier] = value.ToObjectValue(); | |
modifiedKeys.Add(identifier); | |
return ValueTask.FromResult(value); | |
}; | |
template.Render(context); | |
return modifiedKeys.Distinct(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment