### start Source: https://liquidjs.com/api/classes/ParseStream.html Initiates the parsing process. ```APIDOC ## start ### Signature ```typescript start(): ParseStream ``` ### Returns * `ParseStream` - The ParseStream instance. ``` -------------------------------- ### Install LiquidJS via npm Source: https://liquidjs.com/api/index.html Install the LiquidJS package using npm for use in Node.js projects. ```bash npm install liquidjs ``` -------------------------------- ### LiquidJS Template Example Source: https://liquidjs.com/api/index.html Demonstrates basic Liquid syntax with conditional tags and output interpolation, including filters like 'append', 'capitalize'. ```liquid {% if username %} {{ username | append: ", welcome to LiquidJS!" | capitalize }} {% endif %} ``` -------------------------------- ### Offset Loop Start Source: https://liquidjs.com/tags/for.html Skips a specified number of items from the beginning of the collection before starting the loop. Use 'offset' to start processing from a particular item. ```liquid {% for item in array offset:2 %} {{- item -}} {% endfor %} ``` -------------------------------- ### Jekyll Include Syntax Example Source: https://liquidjs.com/tags/include.html Demonstrates the Jekyll include syntax enabled by the 'jekyllInclude' option. Parameters are accessed under the 'include' variable in the partial template. ```liquid {% include article.html header="HEADER" content="CONTENT" %} ``` -------------------------------- ### Modulo Filter Examples Source: https://liquidjs.com/filters/modulo.html Demonstrates the usage of the modulo filter with different inputs. This filter is useful for calculations involving remainders. ```liquid {{ 3 | modulo: 2 }} ``` ```liquid {{ 24 | modulo: 7 }} ``` ```liquid {{ 183.357 | modulo: 12 }} ``` -------------------------------- ### Basic Usage in Node.js Source: https://liquidjs.com/tutorials/setup.html Initialize LiquidJS and render a simple template with a variable. Ensure you have installed the package via npm. ```javascript var { Liquid } = require('liquidjs'); var engine = new Liquid(); engine .parseAndRender('{{name | capitalize}}', {name: 'alice'}) .then(console.log); // outputs 'Alice' ``` -------------------------------- ### arguments Source: https://liquidjs.com/api/classes/Output.html Gets the arguments for the output. ```APIDOC ## arguments ### Description Returns the arguments associated with this output. ### Returns * Arguments - The arguments. ``` -------------------------------- ### get Method Source: https://liquidjs.com/api/classes/Context.html Retrieves a value from the context. Deprecated, use `_get()` or `getSync()` instead. ```APIDOC ## get * get(paths): unknown * #### Parameters * paths: PropertyKey[] #### Returns unknown #### Deprecated use `_get()` or `getSync()` instead ``` -------------------------------- ### Using the echo tag with filters Source: https://liquidjs.com/tags/echo.html This example demonstrates how to use the echo tag to output a variable, apply filters like 'append' and 'capitalize', and render the result. ```liquid {% assign username = 'Bob' %} {% echo username | append: ", welcome to LiquidJS!" | capitalize %} ``` -------------------------------- ### Exponential Memory Growth Example Source: https://liquidjs.com/tutorials/security-model.html This snippet illustrates how memory usage can grow exponentially with each iteration in a loop, even with a small number of initial items. `memoryLimit` helps manage such growth by tracking LiquidJS-specific allocations. ```liquid {% assign array = "1,2,3" | split: "," %} {% for i in (1..32) %} {% assign array = array | concat: array %} {% endfor %} ``` -------------------------------- ### Limit Render Time with Loops Source: https://liquidjs.com/tutorials/security-model.html This example demonstrates a potentially long-running render operation due to a large loop count. Use `renderLimit` to prevent such scenarios from consuming excessive resources. ```liquid {%- for i in (1..10000000) -%} order: {{i}} {%- endfor -%} ``` -------------------------------- ### Basic Usage in TypeScript Source: https://liquidjs.com/tutorials/setup.html Initialize LiquidJS and render a template using TypeScript syntax. This requires type definitions to be installed. ```typescript import { Liquid } from 'liquidjs'; const engine = new Liquid(); engine .parseAndRender('{{name | capitalize}}', {name: 'alice'}) .then(console.log); // outputs 'Alice' ``` -------------------------------- ### Example of Custom Delimiters in LiquidJS Template Source: https://liquidjs.com/tutorials/options.html This example demonstrates using custom output delimiters (`<%=` and `%>`) within a LiquidJS template to output a username and a welcome message. ```html <%= username | append: ", welcome to LiquidJS!" %> ``` -------------------------------- ### Using unshift to Prepend an Element Source: https://liquidjs.com/filters/unshift.html This example demonstrates how to use the unshift filter to add 'apples' to the beginning of the 'fruits' array. The original array is not modified. ```liquid {% assign fruits = "oranges, peaches" | split: ", " %} {% assign everything = fruits | unshift: "apples" %} {% for item in everything %} - {{ item }} {% endfor %} ``` -------------------------------- ### Loop and Filter Example in LiquidJS Source: https://liquidjs.com/playground.html This snippet demonstrates iterating over an array of strings using a LiquidJS for loop and applying filters like 'prepend' and 'capitalize' to format the output within an HTML list. ```liquid ``` ```json { "people": [ "alice", "bob", "carol" ] } ``` -------------------------------- ### Filter Products by Type using reject_exp Source: https://liquidjs.com/filters/reject_exp.html Use `reject_exp` to create a new array that omits items matching a specific condition. This example filters out products of type 'kitchen'. ```liquid All products: {% for product in products %} - {{ product.title }} {% endfor %} {% assign non_kitchen_products = products | reject_exp: "item", "item.type == 'kitchen'" %} Kitchen products: {% for product in non_kitchen_products %} - {{ product.title }} {% endfor %} ``` -------------------------------- ### Map categories with compact Source: https://liquidjs.com/filters/compact.html This example demonstrates using the compact filter after mapping the 'category' attribute to remove any nil values, resulting in a clean array of existing categories. ```liquid {% assign site_categories = site.pages | map: "category" | compact %} {% for category in site_categories %} - {{ category }} {% endfor %} ``` -------------------------------- ### Using the push filter in LiquidJS Source: https://liquidjs.com/filters/push.html This example demonstrates how to use the push filter to add 'peaches' to an existing array of fruits. The original array remains unmodified. ```liquid {% assign fruits = "apples, oranges" | split: ", " %} {% assign everything = fruits | push: "peaches" %} {% for item in everything %} - {{ item }} {% endfor %} ``` -------------------------------- ### LiquidJS Repeat Tag Example Source: https://liquidjs.com/tutorials/render-tag-content.html This Liquid template demonstrates the usage of a custom 'repeat' tag, which renders its content multiple times and provides an iteration index. ```liquid {% repeat %} {{ repeat.i }}. {{ "hello world!" | capitalize }} {% endrepeat %} ``` -------------------------------- ### Get Array Length with size Filter Source: https://liquidjs.com/filters/size.html Apply the size filter to an array to retrieve the number of items it contains. This example first splits a string into an array. ```liquid {% assign my_array = "apples, oranges, peaches, plums" | split: ", " %} {{ my_array.size }} ``` -------------------------------- ### Constructor Source: https://liquidjs.com/api/classes/Context.html Initializes a new Context instance. ```APIDOC ## constructor * new Context(env?, opts?, renderOptions?, __namedParameters?): Context * #### Parameters * env: object = {} * opts: NormalizedFullOptions = defaultOptions * renderOptions: RenderOptions = {} * __namedParameters: { [key: string]: Limiter; } = {} * ##### [key: string]: Limiter #### Returns Context ``` -------------------------------- ### constructor Source: https://liquidjs.com/api/classes/Output.html Constructs a new Output instance. ```APIDOC ## constructor ### Description Initializes a new instance of the Output class. ### Parameters * **token** (OutputToken) - The token associated with the output. * **liquid** (Liquid) - The Liquid instance. ### Returns * Output - A new Output instance. ``` -------------------------------- ### Slice String with Start Index and Length Source: https://liquidjs.com/filters/slice.html Extracts a substring starting from the specified index with a defined length. ```liquid {{ "Liquid" | slice: 2, 5 }} ``` -------------------------------- ### Enable Jekyll Include Syntax Source: https://liquidjs.com/tutorials/options.html Use Jekyll-like include syntax where filenames are static, parameters use '=' instead of ':', and parameters are accessed via the 'include' variable. Defaults to false. ```liquid // entry template {% include article.html header="HEADER" content="CONTENT" %} // article.html
{{include.header}}
{{include.content}}
``` -------------------------------- ### Constructor Source: https://liquidjs.com/api/classes/Liquid.html Initializes a new instance of the Liquid class. ```APIDOC ## constructor * new Liquid(opts?): Liquid * #### Parameters * opts: LiquidOptions = {} #### Returns Liquid ``` -------------------------------- ### Get String Length with size Filter Source: https://liquidjs.com/filters/size.html Use the size filter with pipe notation to get the character count of a string. ```liquid {{ "Ground control to Major Tom." | size }} ``` -------------------------------- ### Slice String from Start Index Source: https://liquidjs.com/filters/slice.html Extracts a substring starting from the specified index. If no length is provided, it returns characters from the index to the end of the string. ```liquid {{ "Liquid" | slice: 0 }} ``` ```liquid {{ "Liquid" | slice: 2 }} ``` -------------------------------- ### Slice String with Negative Start Index Source: https://liquidjs.com/filters/slice.html Extracts a substring using a negative start index, which counts from the end of the string. An optional length can also be specified. ```liquid {{ "Liquid" | slice: -3, 2 }} ``` -------------------------------- ### Configure Template Root and Render File Source: https://liquidjs.com/tutorials/render-file.html Set the root directory for template files and use `renderFile` to render a specific template. Ensure the `extname` is set if your template files use a custom extension. ```javascript var engine = new Liquid({ root: path.resolve(__dirname, 'views/'), // root for layouts/includes lookup extname: '.liquid' // used for layouts/includes, defaults "" }); engine .renderFile("hello", {name: 'alice'}) // will read and render `views/hello.liquid` .then(console.log) // outputs "Alice" ``` -------------------------------- ### Token Constructor Source: https://liquidjs.com/api/classes/Token.html Initializes a new Token instance. ```APIDOC ## constructor ### Description Initializes a new Token instance. ### Signature `new Token(kind: TokenKind, input: string, begin: number, end: number, file?: string): Token` ### Parameters * **kind** (TokenKind) - The type of the token. * **input** (string) - The input string associated with the token. * **begin** (number) - The starting position of the token in the input. * **end** (number) - The ending position of the token in the input. * **file** (string, Optional) - The file path where the token was found. ``` -------------------------------- ### Get Distinct Variables from Template Source: https://liquidjs.com/tutorials/static-analysis.html Use `Liquid.variables(template)` to get an array of distinct variable names used in a template. This includes variables from tag and filter arguments, as well as nested variables. ```javascript import { Liquid } from 'liquidjs' const engine = new Liquid() const template = engine.parse(`

{% assign title = user.title | capitalize %} {{ title }} {{ user.first_name | default: user.name }} {{ user.last_name }} {% if user.address %} {{ user.address.line1 }} {% else %} {{ user.email_addresses[0] }} {% for email in user.email_addresses %} - {{ email }} {% endfor %} {% endif %} {{ a[b.c].d }}

`) console.log(engine.variablesSync(template)) ``` -------------------------------- ### Custom Abstract File System Implementation Source: https://liquidjs.com/tutorials/render-file.html Define a custom file system for LiquidJS by providing an object with methods like `readFileSync`, `readFile`, `existsSync`, `exists`, `contains`, and `resolve`. This example shows fetching templates from a database. ```javascript var engine = new Liquid({ fs: { readFileSync (file) { return db.model('Template').findByIdSync(file).text }, async readFile (file) { const template = await db.model('Template').findById(file) return template.text }, existsSync () { return true }, async exists () { return true }, contains () { return true }, resolve(root, file, ext) { return file } } }); ``` -------------------------------- ### Basic Layout Usage Source: https://liquidjs.com/tags/layout.html Introduce a layout template for the current template to render in. The directory for layout files is defined by `layouts` or `root` options. ```liquid // default-layout.liquid Header {% block %}{% endblock %} Footer // page.liquid {% layout "default-layout.liquid" %} {% block %}My page content{% endblock %} // result Header My page content Footer ``` -------------------------------- ### Parse and Render Template from File Source: https://liquidjs.com/tutorials/caching.html Parse a template file once and render it multiple times with different contexts. The file content should be static. ```javascript var tpl = engine.parseFileSync('hello'); // contents of `hello.liquid`: {{name}} engine.renderSync(tpl, {name: 'alice'}) // 'Alice' engine.renderSync(tpl, {name: 'bob'}) // 'Bob' ``` -------------------------------- ### value Source: https://liquidjs.com/api/classes/Output.html Gets the value of the output. ```APIDOC ## value ### Description Retrieves the value of this output. ### Returns * Value - The value. ``` -------------------------------- ### Render Template from CLI Source: https://liquidjs.com/api/index.html Render a Liquid template directly from the command line using npx, providing template content and context data. ```bash npx liquidjs --template 'Hello, {{ name }}!' --context '{"name": "Snake"}' ``` -------------------------------- ### token Source: https://liquidjs.com/api/classes/Output.html Gets the token associated with the output. ```APIDOC ## token ### Description Retrieves the token associated with this output. ### Returns * OutputToken - The token. ``` -------------------------------- ### postfix Source: https://liquidjs.com/api/classes/Expression.html Gets the postfix representation of the expression tokens. ```APIDOC ## `Readonly` postfix ### Description Gets the postfix representation of the expression tokens. ### Property `postfix: Token[]` ``` -------------------------------- ### constructor Source: https://liquidjs.com/api/classes/Expression.html Initializes a new instance of the Expression class. ```APIDOC ## constructor ### Description Initializes a new instance of the Expression class. ### Signature `new Expression(tokens: IterableIterator): Expression` ### Parameters * `tokens` (IterableIterator) - An iterator of tokens to form the expression. ``` -------------------------------- ### Tokenizer Constructor Source: https://liquidjs.com/api/classes/Tokenizer.html Initializes a new Tokenizer instance with the input string, optional operators, file name, and range. ```APIDOC ## constructor ### Description Initializes a new Tokenizer instance. ### Signature `new Tokenizer(input: string, operators?: Operators, file?: string, range?: [number, number]): Tokenizer` ### Parameters * **input**: `string` - The input string to tokenize. * **operators**: `Operators` (optional) - The operators to use for tokenization. Defaults to `defaultOptions.operators`. * **file**: `string` (optional) - The name of the file being tokenized. * **range**: `[number, number]` (optional) - The starting range [begin, end] for tokenization. ``` -------------------------------- ### Enable Dynamic Partials Source: https://liquidjs.com/tutorials/options.html Allow filename arguments in include, render, and layout tags to be treated as variables. Defaults to true. Setting to false allows simpler syntax for static template relations. ```liquid {% include file %} ``` ```liquid {% liquid foo.html %} ``` -------------------------------- ### Get Last Item of String Array Source: https://liquidjs.com/filters/last.html Use the 'last' filter after splitting a string into an array to retrieve the final element. ```liquid {{ "Ground control to Major Tom." | split: " " | last }} ``` -------------------------------- ### LiquidJS replace_first Filter Example Source: https://liquidjs.com/filters/replace_first.html Use the replace_first filter to substitute the initial instance of a specified substring. This filter is case-sensitive. ```liquid {{ "Take my protein pills and put my helmet on" | replace_first: "my", "your" }} ``` -------------------------------- ### prepareStackTrace Source: https://liquidjs.com/api/classes/AssertionError.html Optional override for formatting stack traces. ```APIDOC ## prepareStackTrace ### Description Optional override for formatting stack traces. ### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ### Property - **prepareStackTrace** ((err: Error, stackTraces: CallSite[]) => any) - Optional function to format stack traces. ``` -------------------------------- ### Table Row with Offset Source: https://liquidjs.com/tags/tablerow.html Use the `offset` parameter to start the tablerow iteration after a specific index. This allows you to skip initial items in a collection. ```liquid {% tablerow product in collection.products cols:2 offset:3 %} {{ product.title }} {% endtablerow %} ``` -------------------------------- ### spawn Method Source: https://liquidjs.com/api/classes/Context.html Creates a new context spawned from the current one. ```APIDOC ## spawn * spawn(scope?): Context * #### Parameters * scope: {} = {} #### Returns Context ``` -------------------------------- ### Add Inline Comments to Liquid Templates Source: https://liquidjs.com/tags/inline_comment.html Use inline comments to exclude text from rendering. Each line within the comment must start with '#'. ```liquid Anything inside an inline comment tag will not be printed. {% # this is an inline comment %} But every line must start with a '#'. {% # this is a comment # that spans multiple lines %} ``` -------------------------------- ### Register LiquidJS as Express View Engine Source: https://liquidjs.com/tutorials/use-in-expressjs.html Set up LiquidJS to be used as the default template engine for your Express application. Ensure 'liquidjs' is installed. ```javascript var { Liquid } = require('liquidjs'); var engine = new Liquid(); // register liquid engine app.engine('liquid', engine.express()); app.set('views', './views'); // specify the views directory app.set('view engine', 'liquid'); // set liquid to default ``` -------------------------------- ### render Source: https://liquidjs.com/api/classes/Output.html Renders the output in the given context. ```APIDOC ## render ### Description Renders the output within the provided context and emits the result. ### Parameters * **ctx** (Context) - The rendering context. * **emitter** (Emitter) - The emitter to send the rendered output to. ### Returns * IterableIterator - An iterator for the rendering process. ``` -------------------------------- ### Customize Output Delimiters in LiquidJS Source: https://liquidjs.com/tutorials/options.html Modify `outputDelimiterLeft` and `outputDelimiterRight` to change the delimiters for output tags, preventing conflicts with other languages. For example, setting them to `<%=` and `%>`. ```javascript const engine = new Liquid({ outputDelimiterLeft: '<%=\n', outputDelimiterRight: '%>' }); ``` -------------------------------- ### ForTag Constructor Source: https://liquidjs.com/api/classes/ForTag.html Initializes a new instance of the ForTag class. ```APIDOC ## constructor ### Description Initializes a new instance of the ForTag class. ### Signature `new ForTag(token: TagToken, remainTokens: TopLevelToken[], liquid: Liquid, parser: Parser): ForTag` ### Parameters * **token** (TagToken) - The token representing the for tag. * **remainTokens** (TopLevelToken[]) - The remaining tokens to be processed. * **liquid** (Liquid) - The Liquid instance. * **parser** (Parser) - The parser instance. ``` -------------------------------- ### Decrement Tag Output Example Source: https://liquidjs.com/tags/decrement.html This shows the output of calling the decrement tag multiple times. Each call decrements the variable's value. ```text -1 -2 -3 ``` -------------------------------- ### TagToken Constructor Source: https://liquidjs.com/api/classes/TagToken.html Initializes a new TagToken instance. ```APIDOC ## constructor ### Description Creates a new TagToken. ### Signature `new TagToken(input: string, begin: number, end: number, options: NormalizedFullOptions, file?: string): TagToken` ### Parameters * **input** (string) - The input string. * **begin** (number) - The starting index of the token. * **end** (number) - The ending index of the token. * **options** (NormalizedFullOptions) - The normalization options. * **file** (string, Optional) - The file path. ``` -------------------------------- ### _renderFile Source: https://liquidjs.com/api/classes/Liquid.html Renders a file with a given context and render file options. ```APIDOC ### _renderFile * _renderFile(file, ctx, renderFileOptions): Generator * #### Parameters * file: string * ctx: undefined | object | Context * renderFileOptions: RenderFileOptions #### Returns Generator ``` -------------------------------- ### Get Full Variable Paths from Template Source: https://liquidjs.com/tutorials/static-analysis.html Use `Liquid.fullVariables(template)` to retrieve a list of all variable paths, including their properties, as strings. This method is asynchronous. ```javascript // continued from above engine.fullVariables(template).then(console.log) ``` -------------------------------- ### renderFile Source: https://liquidjs.com/api/classes/Liquid.html Asynchronously renders a template file with a given context and rendering options. ```APIDOC ## renderFile ### Description Asynchronously renders a template file with a given context and rendering options. ### Parameters * `file`: string - The path to the template file. * `ctx`: object | Context (Optional) - The context to use for rendering. * `renderFileOptions`: RenderFileOptions (Optional) - Options for rendering the file. ### Returns Promise - A promise that resolves to the rendered output. ``` -------------------------------- ### Get First Item After Splitting String Source: https://liquidjs.com/filters/first.html Use the `first` filter after splitting a string to retrieve the first element. This is useful for processing delimited text. ```liquid {{ "Ground control to Major Tom." | split: " " | first }} ``` -------------------------------- ### Get Current Date and Time Source: https://liquidjs.com/filters/date.html Retrieves the current date and time using the special keywords 'now' or 'today'. The timestamp reflects when the page was generated. ```liquid Last updated on: {{ "now" | date: "%Y-%m-%d %H:%M" }} => Last updated on: 2020-03-25 15:57 ``` ```liquid Last updated on: {{ "today" | date: "%Y-%m-%d %H:%M" }} => Last updated on: 2020-03-25 15:57 ``` -------------------------------- ### Pass Context from File via CLI Source: https://liquidjs.com/tutorials/setup.html Provide context data for template rendering by specifying a JSON file path using the '@' prefix. ```bash npx liquidjs --template 'Hello, {{ name }}!' --context @./some-context.json ``` -------------------------------- ### Render Template from CLI Source: https://liquidjs.com/tutorials/setup.html Render a LiquidJS template directly from the command line using npx. The template can be provided inline. ```bash npx liquidjs --template '{{"hello" | capitalize}}' ``` -------------------------------- ### Render Template from File via CLI Source: https://liquidjs.com/tutorials/setup.html Render a LiquidJS template by specifying its path using the '@' prefix. The template content will be read from the specified file. ```bash npx liquidjs --template @./some-template.liquid ``` -------------------------------- ### Reverse an Array in LiquidJS Source: https://liquidjs.com/filters/reverse.html Use the reverse filter to change the order of elements in an array. This example demonstrates reversing a comma-separated string after splitting it into an array. ```liquid {% assign my_array = "apples, oranges, peaches, plums" | split: ", " %} {{ my_array | reverse | join: ", " }} ``` -------------------------------- ### Rejecting Products by Type Source: https://liquidjs.com/filters/reject.html Use the reject filter to exclude products of a specific type from a list. This example filters out items where the 'type' property is 'kitchen'. ```liquid {% assign non_kitchen_products = products | reject: "type", "kitchen" %} ``` -------------------------------- ### _get Method Source: https://liquidjs.com/api/classes/Context.html Retrieves values from the context based on a path. ```APIDOC ## _get * _get(paths): IterableIterator * #### Parameters * paths: (Drop | PropertyKey)[] #### Returns IterableIterator ``` -------------------------------- ### Basic Increment Usage Source: https://liquidjs.com/tags/increment.html Demonstrates the basic usage of the increment tag. Each call to `increment my_counter` increases the variable's value by one, starting from 0. ```liquid {% increment my_counter %} {% increment my_counter %} {% increment my_counter %} ``` -------------------------------- ### liquidMethodMissing Source: https://liquidjs.com/api/classes/Drop.html Handles missing liquid methods by looking up a key in the context. ```APIDOC ## liquidMethodMissing ### Description Handles missing liquid methods by looking up a key in the context. ### Method liquidMethodMissing(key, context) ### Parameters #### Path Parameters - **key** (string | number) - Required - The key to look up. - **context** (Context) - Required - The rendering context. #### Returns any ``` -------------------------------- ### Pop Last Element from Array in LiquidJS Source: https://liquidjs.com/filters/pop.html Use the pop filter to get a new array with the last element removed. This operation does not alter the original array. ```liquid {% assign fruits = "apples, oranges, peaches" | split: ", " %} {% assign everything = fruits | pop %} {% for item in everything %} - {{ item }} {% endfor %} ``` -------------------------------- ### Get Absolute Value of Positive Number with abs Filter Source: https://liquidjs.com/filters/abs.html The abs filter returns the number itself if it is already positive. This demonstrates its behavior with positive numeric inputs. ```liquid {{ 4 | abs }} ``` -------------------------------- ### Render Partials with Variables Source: https://liquidjs.com/tutorials/partials-and-layouts.html Use the `render` tag to include partials. You can pass variables directly or as a hash. The `.liquid` extension can be omitted if configured. ```liquid color: '{{ color }}' shape: '{{ shape }}' ``` ```liquid {% assign shape = 'circle' %} {% render 'color.liquid' %} {% render 'color.liquid' with 'red' %} {% render 'color.liquid', color: 'yellow', shape: 'square' %} ``` -------------------------------- ### Configure Multiple Template Roots Source: https://liquidjs.com/tutorials/render-file.html Specify multiple directories for template lookup by providing an array to the `root` option. This also shows configuration for `partials` and `layouts` directories. ```javascript var engine = new Liquid({ root: ['views/'], partials: ['views/partials/'], layouts: ['views/layouts/'], extname: '.liquid' }); ``` -------------------------------- ### Render Template from Stdin via CLI Source: https://liquidjs.com/tutorials/setup.html Render a LiquidJS template by piping its content to the CLI using the '@-' specifier for stdin. ```bash echo '{{"hello" | capitalize}}' | npx liquidjs --template @- ``` -------------------------------- ### Convert Array to Sentence String (Custom Connector) Source: https://liquidjs.com/filters/array_to_sentence_string.html This example shows how to use the array_to_sentence_string filter with a custom connector, such as 'or', to change the conjunction used in the sentence. ```Liquid {{ "foo,bar,baz" | split: "," | array_to_sentence_string: "or" }} ``` -------------------------------- ### Get Segmented Variable Paths from Template Source: https://liquidjs.com/tutorials/static-analysis.html Use `Liquid.variableSegments(template)` to obtain an array of strings and numbers representing each variable's path segments. This method is asynchronous. ```javascript // continued from above engine.variableSegments(template).then(console.log) ``` -------------------------------- ### LayoutTag Constructor Source: https://liquidjs.com/api/classes/LayoutTag.html Initializes a new instance of the LayoutTag class. ```APIDOC ## Constructor ### Signature new LayoutTag(token: TagToken, remainTokens: TopLevelToken[], liquid: Liquid, parser: Parser): LayoutTag ### Parameters * **token** (TagToken) - The tag token associated with the layout tag. * **remainTokens** (TopLevelToken[]) - The remaining tokens to be processed. * **liquid** (Liquid) - The Liquid instance. * **parser** (Parser) - The parser instance. ``` -------------------------------- ### Default Whitespace Output in LiquidJS Source: https://liquidjs.com/tutorials/whitespace-control.html By default, LiquidJS tags and output markups generate newlines and indentation. This example shows the default behavior before applying whitespace control. ```liquid {% author = "harttle" %} {{ author }} ``` ```text harttle ``` -------------------------------- ### plugin Source: https://liquidjs.com/api/classes/Liquid.html Registers a plugin with the Liquid instance. ```APIDOC ## plugin ### Description Registers a plugin with the Liquid instance. ### Parameters * `plugin`: ((this: Liquid, L: typeof Liquid) => void) - The plugin function to register. * `this`: Liquid - The Liquid instance. * `L`: typeof Liquid - The Liquid class. ### Returns void ``` -------------------------------- ### LiquidJS 'and' Operator Example Source: https://liquidjs.com/tutorials/operators.html The 'and' operator returns true only if both conditions it connects are true. Use it to enforce multiple criteria for an action, such as age and verification status. ```liquid {% if user.age >= 18 and user.verified %} Access granted {% endif %} ``` -------------------------------- ### Constructor Source: https://liquidjs.com/api/classes/RenderError.html Initializes a new instance of the RenderError class. ```APIDOC ## new RenderError(err, tpl) ### Description Creates a new RenderError instance. ### Parameters * **err**: Error - The original error object. * **tpl**: Template - The template associated with the error. ``` -------------------------------- ### Round to Specific Decimal Places Source: https://liquidjs.com/filters/round.html Provide a number as an argument to the 'round' filter to specify the number of decimal places to round to. This example rounds to 2 decimal places. ```liquid {{ 183.357 | round: 2 }} ``` -------------------------------- ### RangeToken Constructor Source: https://liquidjs.com/api/classes/RangeToken.html Initializes a new RangeToken instance. ```APIDOC ## constructor ### Description Initializes a new RangeToken. ### Signature `new RangeToken(input: string, begin: number, end: number, lhs: ValueToken, rhs: ValueToken, file?: string): RangeToken` ### Parameters * **input** (string) - The input string for the token. * **begin** (number) - The starting position of the token. * **end** (number) - The ending position of the token. * **lhs** (ValueToken) - The left-hand side value token. * **rhs** (ValueToken) - The right-hand side value token. * **file** (string, Optional) - The file associated with the token. ``` -------------------------------- ### Set Default File Extension Source: https://liquidjs.com/tutorials/options.html Define a default extension name to append to filenames if they lack one. Defaults to an empty string (disabled). Setting to '.liquid' will load 'foo.liquid' when 'foo' is rendered. ```liquid {% render "foo" %} ``` ```liquid {% render "foo.html" %} ``` -------------------------------- ### Parse and Render Template from String Source: https://liquidjs.com/tutorials/caching.html Parse a template string once and render it multiple times with different contexts. Ensure the template string is static. ```javascript var tpl = engine.parse('{{name | capitalize}}'); engine.renderSync(tpl, {name: 'alice'}) // 'Alice' engine.renderSync(tpl, {name: 'bob'}) // 'Bob' ``` -------------------------------- ### Get Global Variable Segments Source: https://liquidjs.com/tutorials/static-analysis.html Use `Liquid.globalVariableSegments(template)` to extract variable segments that are expected to be globally provided by the application, excluding those defined within the template itself. This method is asynchronous. ```javascript // continued from above engine.globalVariableSegments(template).then(console.log) ``` -------------------------------- ### snapshot Source: https://liquidjs.com/api/classes/Tokenizer.html Creates a snapshot of the current input state. ```APIDOC ## snapshot ### Description Creates a snapshot of the current input state. ### Method snapshot ### Parameters #### Path Parameters - **begin** (number) - Optional - The starting position for the snapshot. Defaults to the current position. ### Returns string ``` -------------------------------- ### Access First Item of an Array Variable Source: https://liquidjs.com/filters/first.html Access the first item of an array stored in a variable using dot notation. This is a common way to get the initial value from a collection. ```liquid {% assign my_array = "zebra, octopus, giraffe, tiger" | split: ", " %} {{ my_array.first }} ``` -------------------------------- ### Get Absolute Value from String Input with abs Filter Source: https://liquidjs.com/filters/abs.html The abs filter can also process strings that contain only a number. It will convert the string to a number and return its absolute value. ```liquid {{ "-19.86" | abs }} ``` -------------------------------- ### getAll Method Source: https://liquidjs.com/api/classes/Context.html Retrieves all scopes within the context. ```APIDOC ## getAll * getAll(): Scope * #### Returns Scope ``` -------------------------------- ### Get Absolute Value of Negative Number with abs Filter Source: https://liquidjs.com/filters/abs.html Use the abs filter to convert a negative number to its positive equivalent. This filter works directly on numeric types. ```liquid {{ -17 | abs }} ``` -------------------------------- ### RenderTag Constructor Source: https://liquidjs.com/api/classes/RenderTag.html Initializes a new instance of the RenderTag class. ```APIDOC ## constructor ### Description Initializes a new instance of the RenderTag class. ### Signature `new RenderTag(token: TagToken, remainTokens: TopLevelToken[], liquid: Liquid, parser: Parser): RenderTag` ### Parameters * **token** (TagToken) - The tag token associated with this render tag. * **remainTokens** (TopLevelToken[]) - The remaining tokens to be processed. * **liquid** (Liquid) - The Liquid instance. * **parser** (Parser) - The parser instance. ``` -------------------------------- ### LiquidJS 'contains' Operator Example Source: https://liquidjs.com/tutorials/operators.html The 'contains' operator checks for the presence of a substring within a string or an element within an array. It's useful for filtering or identifying specific items. ```liquid {% if product.title contains "Pack" %} This is a pack {% endif %} ``` -------------------------------- ### LiquidJS 'not' Operator Example Source: https://liquidjs.com/tutorials/operators.html Use the 'not' operator to negate a condition. It returns true if the condition is false, and false if the condition is true. This is useful for checking inactive states. ```liquid {% if not user.active %} User is inactive {% endif %} ``` -------------------------------- ### LiquidJS Options Source: https://liquidjs.com/api/interfaces/LiquidOptions.html These are the optional configuration parameters for LiquidJS. ```APIDOC ## LiquidJS Options ### Description Configuration options for the LiquidJS rendering engine. ### Parameters #### Optional Parameters - **orderedFilterParameters** (boolean) - Optional - Respect parameter order when using filters like "for ... reversed limit". Defaults to `false`. - **outputDelimiterLeft** (string) - Optional - The left delimiter for liquid outputs. - **outputDelimiterRight** (string) - Optional - The right delimiter for liquid outputs. - **outputEscape** (OutputEscapeOption) - Optional - Default escape filter applied to output values. Defaults to `undefined`. - **ownPropertyOnly** (boolean) - Optional - Hide scope variables from prototypes. Defaults to `false`. - **parseLimit** (number) - Optional - Limit total length of templates parsed in one `parse()` call for DoS handling. - **partials** (string | string[]) - Optional - A directory or an array of directories from where to resolve included templates. Defaults to `root`. - **preserveTimezones** (boolean) - Optional - Whether input strings to date filter preserve the given timezone. - **relativeReference** (boolean) - Optional - Allow refer to layouts/partials by relative pathname. Defaults to `true`. - **renderLimit** (number) - Optional - Limit total time (in ms) for each `render()` call for DoS handling. - **root** (string | string[]) - Optional - A directory or an array of directories from where to resolve layout and include templates. Defaults to `["."]`. - **strictFilters** (boolean) - Optional - Whether or not to assert filter existence. Defaults to `false`. - **strictVariables** (boolean) - Optional - Whether or not to assert variable existence. Defaults to `false`. - **tagDelimiterLeft** (string) - Optional - The left delimiter for liquid tags. - **tagDelimiterRight** (string) - Optional - The right delimiter for liquid tags. - **templates** ({ [key: string]: string }) - Optional - Render from in-memory `templates` mapping instead of file system. - **timezoneOffset** (string | number) - Optional - JavaScript timezone name or timezoneOffset for `date` filter. Defaults to local time. - **trimOutputLeft** (boolean) - Optional - Strip blank characters from the left of values until `\n` (inclusive). Defaults to `false`. - **trimOutputRight** (boolean) - Optional - Strip blank characters from the right of values (`{{ }}`) until `\n` (inclusive). Defaults to `false`. - **trimTagLeft** (boolean) - Optional - Strip blank characters from the left of tags (`{% %}`) until `\n` (inclusive). Defaults to `false`. - **trimTagRight** (boolean) - Optional - Strip blank characters from the right of tags (`{% %}`) until `\n` (inclusive). Defaults to `false`. ``` -------------------------------- ### Rejecting Products with Truthy Taxable Value Source: https://liquidjs.com/filters/reject.html When no target value is provided, reject filters out elements where the specified property has a truthy value. This example removes products that are marked as 'taxable'. ```liquid {% assign not_taxed_products = products | reject: "taxable" %} ``` -------------------------------- ### NumberToken Constructor Source: https://liquidjs.com/api/classes/NumberToken.html Initializes a new instance of the NumberToken class. ```APIDOC ## constructor ### Description Creates a new NumberToken. ### Signature `new NumberToken(input: string, begin: number, end: number, file?: string): NumberToken` ### Parameters * `input` (string) - The input string. * `begin` (number) - The starting position of the token. * `end` (number) - The ending position of the token. * `file` (string, Optional) - The file associated with the token. ``` -------------------------------- ### Analyze Global Variables with Partial Templates Source: https://liquidjs.com/tutorials/static-analysis.html When analyzing templates that include partials, LiquidJS analyzes them by default. Use `Liquid.globalVariables(template)` to get global variables, considering included partials. ```javascript import { Liquid } from 'liquidjs' const footer = `

© {{ "now" | date: "%Y" }} {{ site_name }}

{{ site_description }}

` const engine = new Liquid({ templates: { footer } }) const template = engine.parse(`

Hi, {{ you | default: 'World' }}!

{% assign some = 'thing' %} {% include 'footer' %} `) engine.globalVariables(template).then(console.log) ``` -------------------------------- ### Parser Constructor Source: https://liquidjs.com/api/classes/Parser.html Initializes a new instance of the Parser class. ```APIDOC ## constructor ### Description Initializes a new Parser instance. ### Parameters * **liquid** (Liquid) - The Liquid instance to associate with the parser. ### Returns * **Parser** - A new Parser instance. ``` -------------------------------- ### Organize Tag Parsing with ParseStream Source: https://liquidjs.com/tutorials/render-tag-content.html Re-implement tag parsing using ParseStream for a more event-driven and organized approach, especially for complex tags. This example achieves the same functionality as the manual parsing method. ```javascript parse(tagToken, remainTokens) { this.tpls = [] this.liquid.parser.parseStream(remainTokens) .on('template', tpl => this.tpls.push(tpl)) // note that we cannot use arrow function because we need `this` .on('tag:endwrap', function () { this.stop() }) .on('end', () => { throw new Error(`tag ${tagToken.getText()} not closed`) }) .start() } ``` -------------------------------- ### LiquidTag Constructor Source: https://liquidjs.com/api/classes/LiquidTag.html Initializes a new instance of the LiquidTag class. ```APIDOC ## constructor ### Description Initializes a new instance of the LiquidTag class. ### Parameters * **token** (TagToken) - The tag token associated with this tag. * **remainTokens** (TopLevelToken[]) - The remaining tokens to be processed. * **liquid** (Liquid) - The Liquid instance. * **parser** (Parser) - The parser instance. ### Returns LiquidTag - A new instance of LiquidTag. ``` -------------------------------- ### Specify Output File via CLI Source: https://liquidjs.com/tutorials/setup.html Direct the rendered output to a specified file instead of stdout using the --output flag. ```bash npx liquidjs --template '{{"hello" | capitalize}}' --output ./hello.txt ``` -------------------------------- ### Check for Empty Array or String in LiquidJS Source: https://liquidjs.com/tutorials/drops.html The `empty` drop is useful for determining if an array, string, or object has no elements or keys. The example shows rendering text when an author list is empty. ```liquid {% if authors == empty %} Author list is empty {% endif %} ``` -------------------------------- ### LiquidJS 'or' Operator Example Source: https://liquidjs.com/tutorials/operators.html Use the 'or' operator when at least one of the conditions needs to be true for an action to occur. This is helpful for checking elevated privileges based on multiple roles. ```liquid {% if user.isAdmin or user.isModerator %} You have elevated privileges {% endif %} ``` -------------------------------- ### Hash Constructor Source: https://liquidjs.com/api/classes/Hash.html Initializes a new Hash object. It can take an input string or Tokenizer and an optional jekyllStyle parameter. ```APIDOC ## constructor ### Description Initializes a new Hash object. ### Signature `new Hash(input: string | Tokenizer, jekyllStyle?: string | boolean): Hash` ### Parameters * **input** (string | Tokenizer) - The input string or Tokenizer to process. * **jekyllStyle** (string | boolean) - Optional. Specifies Jekyll-style parsing. ``` -------------------------------- ### Find Index of Object in Array - LiquidJS Source: https://liquidjs.com/filters/find_index.html Use the find_index filter to get the 0-based index of the first member in an array whose 'graduation_year' attribute is 2014. Returns nil if no such member exists. ```javascript const members = [ { graduation_year: 2013, name: 'Jay' }, { graduation_year: 2014, name: 'John' }, { graduation_year: 2014, name: 'Jack' } ] ``` ```liquid {{ members | find_index: "graduation_year", 2014 | json }} ``` -------------------------------- ### renderFileSync Source: https://liquidjs.com/api/classes/Liquid.html Synchronously renders a template file with a given context and rendering options. ```APIDOC ## renderFileSync ### Description Synchronously renders a template file with a given context and rendering options. ### Parameters * `file`: string - The path to the template file. * `ctx`: object | Context (Optional) - The context to use for rendering. * `renderFileOptions`: RenderFileOptions (Optional) - Options for rendering the file. ### Returns any - The rendered output. ``` -------------------------------- ### Rejecting with Nested Property Access Source: https://liquidjs.com/filters/reject.html The property argument can be a Liquid variable expression, allowing access to nested properties. This example rejects products based on a nested 'class' property within 'meta.details'. ```javascript const products = [ { meta: { details: { class: 'A' } }, order: 1 }, { meta: { details: { class: 'B' } }, order: 2 }, { meta: { details: { class: 'B' } }, order: 3 } ] ``` ```liquid {% assign selected = products | reject: 'meta.details["class"]', "B" %} ``` -------------------------------- ### FS Interface Methods Source: https://liquidjs.com/api/interfaces/FS.html This section details the methods available in the FS interface for file system operations. ```APIDOC ## `Optional` contains contains?: ((root: string, file: string) => Promise) ### Description Check if file is contained in `root`. Node default fs uses realpath; if omitted, loader assumes contained. ## `Optional` containsSync containsSync?: ((root: string, file: string) => boolean) ### Description Sync check if file is contained in `root`, allows both renderSync and render. ## `Optional` dirname dirname?: ((file: string) => string) ### Description Required for relative path resolving. ## exists exists: ((filepath: string) => Promise) ### Description Check if a file exists asynchronously. ## existsSync existsSync: ((filepath: string) => boolean) ### Description Check if a file exists synchronously. ## `Optional` fallback fallback?: ((file: string) => undefined | string) ### Description Fallback file for lookup failure. ## readFile readFile: ((filepath: string) => Promise) ### Description Read a file asynchronously. ## readFileSync readFileSync: ((filepath: string) => string) ### Description Read a file synchronously. ## resolve resolve: ((dir: string, file: string, ext: string) => string) ### Description Resolve a file against directory, for given `ext` option. ## `Optional` sep sep?: string ### Description Defaults to "/". ``` -------------------------------- ### IncludeTag Constructor Source: https://liquidjs.com/api/classes/IncludeTag.html Initializes a new instance of the IncludeTag class. ```APIDOC ## constructor ### Description Initializes a new instance of the IncludeTag class. ### Signature `new IncludeTag(token: TagToken, remainTokens: TopLevelToken[], liquid: Liquid, parser: Parser): IncludeTag` ### Parameters * **token**: TagToken * **remainTokens**: TopLevelToken[] * **liquid**: Liquid * **parser**: Parser ``` -------------------------------- ### Check Array Inclusion with 'has' Filter Source: https://liquidjs.com/filters/has.html Use the 'has' filter to determine if any object in the 'members' array has a 'graduation_year' of 2014. This example demonstrates a common use case for checking data presence. ```javascript const members = [ { graduation_year: 2013, name: 'Jay' }, { graduation_year: 2014, name: 'John' }, { graduation_year: 2014, name: 'Jack' } ] ``` ```liquid {{ members | has: "graduation_year", 2014 | json }} ``` -------------------------------- ### Render Partial with 'with' Parameter Source: https://liquidjs.com/tags/render.html Use the 'with...as' syntax to pass a single object to a partial template. The variable specified after 'as' will hold the object's value within the partial. ```liquid {% assign featured_product = all_products['product_handle'] %} {% render 'product' with featured_product as product %} ``` -------------------------------- ### Map categories without compact Source: https://liquidjs.com/filters/compact.html This example shows the output when mapping the 'category' attribute from site pages without using the compact filter, resulting in nil values for pages lacking the attribute. ```liquid {% assign site_categories = site.pages | map: "category" %} {% for category in site_categories %} - {{ category }} {% endfor %} ```