-
Notifications
You must be signed in to change notification settings - Fork 0
/
getting-started-with-liquid.liquidbook
1 lines (1 loc) · 14.6 KB
/
getting-started-with-liquid.liquidbook
1
{"dataFolder":"D:\\Temp\\Documentation\\Data","templatesFolder":"D:\\Temp\\Documentation\\Templates","liquidList":["{%- assign sharedTime = \"now\" | date: \"%Y-%m-%d %H:%M:%S\" -%}","{%- assign sharedTime = \"now\" | date: \"%Y-%m-%d %H:%M:%S\" -%}"],"cells":[{"kind":1,"language":"markdown","value":"# Getting Started with Liquid\r\n\r\n[Liquid](https://shopify.github.io/liquid/) is an open-source template language created by [Shopify](https://www.shopify.com/). The input is text based combined with Liquid commands. The text can be anything, like HTML, CSS, JSON and more. Shopify provided a full [reference to the Liquid language](https://shopify.github.io/liquid/basics/introduction/), but in this document we'll go through the basics with some samples.\r\n\r\nLiquid templates have (usually) the extension `.liquid` and the language is a combination of **objects**, **tags** and **filters**. In the rest of this document we show some basic use of these components.\r\n\r\nThis document references a fake dataset. You can download [this fake data zip-file](../.attachments/notebook-fake-dataset.zip) and extract it in a folder on your local disk.\r\n\r\n## Notebook settings\r\n\r\nTo make this notebook work with some fake data, make sure to properly set the paths below to the fake dataset. Download [the fake dataset](../.attachments/notebook-fake-dataset.zip) to your local machine and extract it somewhere. Check the exact path to the Data and Templates folder, paste that in the `Settings` code box below and run the code to activate in this notebook."},{"kind":2,"language":"liquid-notebook-settings","value":"DATA D:\\Temp\\Documentation\\Data\r\nTEMPLATES D:\\Temp\\Documentation\\Templates"},{"kind":1,"language":"markdown","value":"## Objects\r\n\r\nObjects contain the content that Liquid displays on a page. Objects and variables are displayed when enclosed in double curly braces: {{ and }}. Below an example of an object, which you might recognize as a string. It's a bit of a useless use of Liquid, but it demonstrates the basic use:"},{"kind":2,"language":"liquid","value":"This is sample output of just a string {{ \"Hello Liquid!\" }}"},{"kind":1,"language":"markdown","value":"But using objects makes more sense when using real data. The parsing process normally takes the Liquid template as input, but also one or more named data objects that can then be accessed by the template. Below an example where we access the `Model` object and its `Tables` collection to show the name of the first table:"},{"kind":2,"language":"liquid","value":"This is the first table name: {{ model.Tables[0].Name }}"},{"kind":1,"language":"markdown","value":"It's important to be aware that Liquid parsers will never output errors references to non-existing data, except for index out of bounds. For instance, below you see an example of the use of a non existing field and it's output:"},{"kind":2,"language":"liquid","value":"The field NON_EXISTING_FIELD does not exist and outputs '{{ NON_EXISTING_FIELD }}' (so, nothing :D)"},{"kind":1,"language":"markdown","value":"## Tags\r\n\r\nTags create the logic and control flow for templates. The curly brace percentage delimiters **{%** and **%}** and the text that they surround do not produce any visible output when the template is rendered. This lets you assign variables and create conditions or loops without showing any of the Liquid logic on the page.\r\n\r\n### Variable tags\r\n\r\nVariable tags create new Liquid variables that can be referenced in the rest of the code.\r\n\r\n* assign - Creates a new named variable.\r\n* capture - Captures the string inside of the opening and closing tags and assigns it to a string variable.\r\n* increment/decrement - Creates and outputs a counter with initial value 0. On subsequent calls, it increases/decreases its value by one and outputs the new value.\r\n\r\nSee below how these can be used and the output."},{"kind":2,"language":"liquid","value":"{%- comment -%}Assign{%- endcomment -%}\r\n{% assign name = \"Pete Johnson\" -%}\r\nName: {{ name }}\r\n\r\n{%- comment -%}Capture{%- endcomment -%}\r\n{% capture full_sentence %}This is some text combined with the variable name with value '{{ name }}'{% endcapture %}\r\nFull sentence: {{ full_sentence }}\r\n\r\n{% comment -%}Increment/decrement{%- endcomment -%}\r\nFirst call: {% increment index %}\r\nSecond call: {% increment index %}\r\nThird call: {% increment index %}\r\nFourth call (Decrement): {% decrement index -%}"},{"kind":1,"language":"markdown","value":"### Control flow tags\r\n\r\nControl flow tags create conditions that decide whether blocks of Liquid code get executed.\r\n\r\n* if / else / elsif - Executes a block of code only if a certain condition is true and add conditions.\r\n* case / when - Creates a switch statement to execute a particular block of code when a variable has a specified value. case initializes the switch statement, and when statements define the various conditions. An optional else statement at the end of the case provides code to execute if none of the conditions are met.\r\n\r\nSee below how these can be used and the output."},{"kind":2,"language":"liquid","value":"{% assign name = \"anonymous\" -%}\r\n{%- if name == \"Pete\" %}\r\n Hey Pete!\r\n{% elsif name == \"anonymous\" %}\r\n Why don't you tell me your name?\r\n{% else %}\r\n I don't know who you are...\r\n{% endif %}"},{"kind":1,"language":"markdown","value":"### Template tags\r\n\r\nTemplate tags tell Liquid where to disable processing for comments or non-Liquid markup, and how to establish relations among template files.\r\n\r\n* comment - adding comment to your template that won't be rendered.\r\n* include - Insert the rendered content of another template file within the current template.\r\n\r\n> **NOTE:** include is marked obsolete and should be replaced by `render`, however currently it's not working yet. Working with the Fluid team on this issue (https://github.com/sebastienros/fluid/issues/420).\r\n\r\nSee below how these can be used and the output."},{"kind":2,"language":"liquid","value":"{%- comment -%}You've seen comment before, but here it is again{%- endcomment -%}\r\n\r\n{%- comment -%}Render{%- endcomment -%}\r\n{%- comment -%}In this case we include an external template to convert the gender to text{%- endcomment -%}\r\n{%- comment -%}The external template is part of the fake dataset.{%- endcomment -%}\r\n{%- assign patient = model.Patients.Records | first -%}\r\nPatient with gender '{{ patient.gender }}' translated to '{% include 'data-converters/gender', gender: patient.gender %}'"},{"kind":1,"language":"markdown","value":"### Iteration tags\r\n\r\nIteration tags repeatedly run blocks of code.\r\n\r\n* for - Repeatedly executes a block of code.\r\n* else - Specifies a fallback case for a for loop which will run if the loop has zero length.\r\n\r\nSee below how these can be used and the output."},{"kind":2,"language":"liquid","value":"{%- comment -%}for loop{%- endcomment -%}\r\nTables in the model:\r\n{% for table in model.Tables -%}\r\n{{ table.Name }}\r\n{% endfor -%}\r\n\r\n{%- comment -%}Make a selection from patients that don't exist (empty array) and process.{%- endcomment -%}\r\n{%- comment -%}For more information on the where filter, see the Filters section below.{%- endcomment -%}\r\n{% assign emptyArray = model.Patients | where: \"name\", \"nobody\" %}\r\nThe result of the loop-else for an empty array:\r\n{% for item in emptyArray -%}\r\n {{ item.Name }}\r\n{% else %}\r\n Found nobody with that name.\r\n{% endfor -%}"},{"kind":1,"language":"markdown","value":"### Special note on spacing\r\n\r\nThrough the samples above you might have noticed the use of the - (dash) character on and off. The dash in combination with tags take care of spacing. Using a dash at the beginning of a tag will eliminate spaces and newlines before that tag. Using a dash at the end will eliminate a newline after that tag. In most case you'll have to fiddle around with these to get the result you want. Especially with for-loops it can get a bit tricky. But don't worry, you'll get the hang of it eventually :p\r\n\r\nBelow some samples of use:"},{"kind":2,"language":"liquid","value":"Line before normal assign\r\n{% assign x = \"some value\" %}\r\nLine after normal assign\r\n\r\nLine before dash in the beginning\r\n{%- assign x = \"some value\" %}\r\nLine after dash in the beginning\r\n\r\nLine before dash at the end\r\n{% assign x = \"some value\" -%}\r\nLine after dash at the end\r\n\r\nLine before dash on both ends\r\n{%- assign x = \"some value\" -%}\r\nLine after dash on both ends"},{"kind":1,"language":"markdown","value":"\r\n## Filters\r\n\r\nFilters change the output of a Liquid object or variable. They are used within double curly braces **{{ }}** and variable assignment, and are separated by a pipe character **|**. There are quite some filters defined in the standard language. A few important ones are in the sections below.\r\n\r\n### String filters\r\n\r\n* downcase / upcase - Makes each character in a string lowercase / uppercase.\r\n* capitalize - Makes the first character of a string capitalized and converts the remaining characters to lowercase.\r\n* replace - Replaces every occurrence of the first argument in a string with the second argument.\r\n* strip_newlines - Removes any newline characters (line breaks) from a string.\r\n\r\nSee below how these can be used and the output."},{"kind":2,"language":"liquid","value":"{% comment -%}Downcase{%- endcomment -%}\r\nDowncase of 'EXAMPLE': {{ \"EXAMPLE\" | downcase }}\r\n\r\n{% comment -%}Upcase{%- endcomment -%}\r\nUpcase of 'example': {{ \"example\" | upcase }}\r\n\r\n{% comment -%}Capitalize{%- endcomment -%}\r\nCapitalize of 'pete johnson': {{ \"pete johnson\" | capitalize }}\r\n\r\n{% comment -%}Replace{%- endcomment -%}\r\nReplace all 'u' in 'bununu' with 'a': {{ \"bununu\" | replace: \"u\", \"a\" }}\r\n\r\n{% comment -%}This sample is a bit more elaborate, as we need something with a newline. \r\nFor more information see the explanation of Tags further down this document.{%- endcomment -%}\r\n{% capture string_with_newlines -%}\r\nHello\r\nLiquid\r\n{%- endcapture -%}\r\n{{ string_with_newlines | strip_newlines }}"},{"kind":1,"language":"markdown","value":"### String- and Array filters\r\n\r\n* first / last - Returns the first / last item of an array.\r\n* size - Returns the number characters in a string or the number of items in an array.\r\n* split - Divides a string into an array using the argument as a separator. split is commonly used to convert comma-separated items from a string to an array.\r\n\r\nSee below how these can be used and the output."},{"kind":2,"language":"liquid","value":"{% comment -%}First{%- endcomment -%}\r\n{% assign table = model.Tables | first -%}\r\nFirst table name: {{ table.Name }}\r\n\r\n{% comment -%}Last{%- endcomment -%}\r\n{% assign table = model.Tables | last -%}\r\nLast table name: {{ table.Name }}\r\n\r\n{% comment -%}Size{%- endcomment -%}\r\nSize of a string 'example text': {{ \"example text\" | size }}\r\nSize of the Tables array: {{ model.Tables | size }}\r\n\r\n{%- comment -%}Split{%- endcomment %}\r\n{% assign teamWindmill = \"Laurent, Jan, Carlos, Ibrahim, Bart, Isabel, Martin\" | split: \", \" %}\r\nTeam Windmill has {{ teamWindmill | size }} members:\r\n{% for member in teamWindmill -%}\r\n {{ member }}\r\n{% endfor -%}"},{"kind":1,"language":"markdown","value":"### Special focus: where filter\r\n\r\nThe **where** filter can be used on arrays to create a new array with only the objects with a given property value. In other words, this is a very simple where-clause.\r\n\r\nImportant to realize is that the result is always an array, even if nothing is returned or if just 1 item is found. If you expect 1 item, you still have to address the first item of the array. For this purpose the `first` filter can be used. You can combine where clauses like an 'AND' by adding more where filters.\r\n\r\nSee below how these can be used and the output."},{"kind":2,"language":"liquid","value":"{% comment -%}First show patients for reference{%- endcomment %}\r\nPatients: \r\n{% for patient in model.Patients.Records -%}\r\n{{ patient.Id }} = {{ patient.Name }} ({{ patient.gender }})\r\n{% endfor -%}\r\n\r\n{% comment -%}Now show just the female patients{%- endcomment %}\r\n{% assign females = model.Patients.Records | where: \"gender\", \"F\" -%}\r\nFemale Patients:\r\n{% for female in females -%}\r\n{{ female.Id }} = {{ female.Name }} ({{ female.gender }})\r\n{% endfor -%}\r\n\r\n{% comment -%}Select a single item (or none) from the collection{%- endcomment %}\r\n{%- assign patient = model.Patients.Records | where: \"Id\", \"1004\" | first %}\r\nSelected patient: {{ patient.Id }} = {{ patient.Name }} ({{ patient.gender }})"},{"kind":1,"language":"markdown","value":"### Other filters worth mentioning\r\n\r\n* date - Converts a timestamp into another date format. To get the current time, pass the special word \"now\" (or \"today\") to date.\r\n* url_encode - Converts any URL-unsafe characters in a string into percent-encoded characters.\r\n* url_decode - Decodes a string that has been encoded as a URL or by url_encode.\r\n\r\nSee below how these can be used and the output."},{"kind":2,"language":"liquid","value":"{%- comment -%}Date{%- endcomment -%}\r\nDate for now with format: {{ \"now\" | date: \"%Y-%m-%d %H:%M:%S\" }}\r\nDate for today with format: {{ \"today\" | date: \"%Y-%m-%d %H:%M:%S\" }}\r\n\r\n{% comment -%}url_encode{%- endcomment -%}\r\nURL encoding 'https://shopify.github.io/liquid/': {{ \"https://shopify.github.io/liquid/\" | url_encode }}\r\nURL encoding 'Pete Johnson': {{ \"Pete Johnson\" | url_encode }}\r\n\r\n{% comment -%}url_decode{%- endcomment -%}\r\n{{ \"%27Liquid%21%27+said+Martin\" | url_decode }}"},{"kind":1,"language":"markdown","value":"## Visual Studio Code extension for Liquid Notebooks\r\n\r\nA useful tool is the Visual Studio Code extension for Liquid Notebooks. Other useful extensions are installed with this extension. The first one is the [Liquid Language Support](https://marketplace.visualstudio.com/items?itemName=neilding.language-liquid) extension for syntax highlighting. The second one is the [Shopify Liquid Template Snippets for VS Code](https://marketplace.visualstudio.com/items?itemName=killalau.vscode-liquid-snippets) extension for adding easy code snippets for Liquid code. A few snippets:\r\n\r\n* `for-` - generates a for loop\r\n* `assign-` - generates an assign statement\r\n\r\nAnd much more are supported. They are listed on the link above of the extension.\r\n\r\n## Playground\r\n\r\nIf you want to experiment with this notebook further, you can use the code block below or create your own. Have fun!"},{"kind":2,"language":"liquid","value":"{{ \"hello liquid playground!\" | capitalize }}"}]}