-
Notifications
You must be signed in to change notification settings - Fork 15
Liquid.NET for Developers
Although the Liquid.NET templating language is very close to Shopify Liquid, the Liquid.NET C# code is very different from the Shopify Ruby implementation.
Parsing a template requires a minimum of three things:
- generate a (LiquidTemplate)[https://github.com/mikebridge/Liquid.NET/blob/master/Liquid.NET/src/LiquidTemplate.cs] object from a string of raw liquid code
- creating a context (which maintains the state of the parsing, like variables)
- merging the two together using LiquidTemplate.Render(ctx:ITemplateContext)
// Parse the liquid string into a LiquidTemplate
LiquidTemplate ast = LiquidTemplate.Create("Hello {{ greeting }}");
// Create a context
ITemplateContext ctx = new TemplateContext()
.DefineLocalVariable("greeting", "World")
.WithAllFilters();
// Merge the context into the template
String result = template.Render(ctx);
// Show the result
Console.WriteLine(result);
==>
"Hello World"Types in liquid are numeric, boolean, string, collection, hash, date, and the special type range. Any of these can take the value "nil". These are represented with C# classes that implement IExpressionConstant.
| liquid | C# |
|---|---|
| boolean | BooleanValue |
| numeric | NumericValue |
| date | DateValue |
| string | StringValue |
| collection | ArrayValue |
| hash | DictionaryValue |
| range* | GeneratorValue |
Ranges are currently only available in a few places---most of the rest of this discussion doesn't apply to them. More on this later.
Arrays and Dictionaries are heterogeneous, so an array can hold a mix of types, and although the keys of a hash are always strings, a value in a dictionary can be of any type.
A numeric has an underlying type, which is int, long, decimal or BigInteger. You can create a NumericValue with the static constructor NumericValue.Create(val). This means that if you create a numeric value with the decimal "3.00", it will render as "3.00". If you do math with two numeric values, it will attempt to use the precision of the most precise value, so an "int" NumericValue times a "decimal" NumericValue will yield a decimal NumericValue.
See How to Write a Filter for more details.
See How to Write a Tag or Block for more details.