### Install and Start React Project Source: https://github.com/harttle/liquidjs/blob/master/demo/reactjs/README.md Use these npm commands to install dependencies and start the development server for the React project. ```bash npm install ``` ```bash npm start ``` -------------------------------- ### Install and Run LiquidJS Demo Source: https://github.com/harttle/liquidjs/blob/master/demo/typescript/README.md Follow these commands to install dependencies, build the project, and start the LiquidJS demo in a TypeScript environment. ```bash cd demo/typescript npm install npm run build npm start ``` -------------------------------- ### Start Local Documentation Server Source: https://github.com/harttle/liquidjs/blob/master/CONTRIBUTING.md Navigate to the docs directory and start the local development server for the playground. ```bash cd docs npm start ``` -------------------------------- ### Install and Build LiquidJS with Webpack Source: https://github.com/harttle/liquidjs/blob/master/demo/webpack/README.md Follow these commands to install dependencies, build the project, and start the application when using LiquidJS with Webpack. ```bash cd demo/nodejs npm install npm run build npm start ``` -------------------------------- ### Example Usage of reject_exp Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/reject_exp.md This example demonstrates how to use reject_exp to filter out kitchen products from a list. It first displays all products and then the filtered list. ```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 %} ``` -------------------------------- ### Liquid Template Example Source: https://github.com/harttle/liquidjs/blob/master/README.md Demonstrates basic Liquid syntax with conditional statements and output tags. ```liquid {% if username %} {{ username | append: ", welcome to LiquidJS!" | capitalize }} {% endif %} ``` -------------------------------- ### Run Performance Benchmark Cases Source: https://github.com/harttle/liquidjs/blob/master/CONTRIBUTING.md Navigate to the benchmark directory, install dependencies, and run the performance test cases. ```bash cd benchmark npm ci npm start ``` -------------------------------- ### Offset Loop Start Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tags/for.md Skips a specified number of initial items before starting the loop iteration. ```liquid {% for item in array offset:2 %} {{- item -}} {% endfor %} ``` -------------------------------- ### Install LiquidJS with npm Source: https://github.com/harttle/liquidjs/blob/master/README.md Install the LiquidJS package using npm for use in Node.js projects. ```bash npm install liquidjs ``` -------------------------------- ### Dynamic Partials Example Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/options.md Illustrates how dynamic partials work by including a file whose name is determined by a scope variable. Defaults to true. ```liquid {% include file %} ``` -------------------------------- ### Liquid Plus Filter Example Source: https://github.com/harttle/liquidjs/wiki/Operators Shows how to add numbers in Liquid using the 'plus' filter, as direct numerical operators are not supported. ```liquid {{ a | plus: b }} ``` -------------------------------- ### Liquid Logic Operators Example Source: https://github.com/harttle/liquidjs/wiki/Operators Illustrates the use of Liquid logic operators for combining conditions. ```liquid {{ a or b }} {{ a and b }} {{ a contains b }} ``` -------------------------------- ### Install Liquid.js via npm Source: https://github.com/harttle/liquidjs/wiki/Home Install the liquidjs package using npm for use in your Node.js projects. ```bash npm install --save liquidjs ``` -------------------------------- ### Liquid Comparison Operators Example Source: https://github.com/harttle/liquidjs/wiki/Operators Demonstrates the usage of Liquid comparison operators for conditional logic. ```liquid {{ a == b }} {{ a != b }} {{ a > b }} {{ a < b }} {{ a >= b }} {{ a <= b }} ``` -------------------------------- ### Install a Plugin to Extend Liquid.js Filters Source: https://context7.com/harttle/liquidjs/llms.txt Shows how to install a plugin that registers custom filters. The 'upup-plugin.js' registers 'upup' (to uppercase) and 'shout' (to uppercase with exclamation marks) filters. ```javascript // upup-plugin.js module.exports = function upupPlugin (Liquid) { this.registerFilter('upup', value => String(value).toUpperCase()) this.registerFilter('shout', (value, times = 1) => String(value).toUpperCase() + '!'.repeat(times) ) } // main.js const { Liquid } = require('liquidjs') const engine = new Liquid() engine.plugin(require('./upup-plugin')) const result = await engine.parseAndRender( '{{ greeting | upup }} | {{ greeting | shout: 3 }}', { greeting: 'hello' } ) console.log(result) // => "HELLO | HELLO!!!" ``` -------------------------------- ### Static Partials Example with dynamicPartials: false Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/options.md Shows how to include a file with a static name when dynamicPartials is set to false. This behavior is less common. ```liquid {% liquid foo.html %} ``` -------------------------------- ### Extname Option Example Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/options.md Demonstrates how the extname option appends a default extension to filenames that lack one, facilitating template loading. Defaults to an empty string. ```liquid {% render "foo" %} there's no extname, adds `.liquid` and loads foo.liquid {% render "foo.html" %} there is an extname already, loads foo.html directly ``` -------------------------------- ### Basic Usage in TypeScript Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/setup.md Shows how to use LiquidJS with TypeScript, leveraging its type definitions for better development experience. Ensure 'liquidjs' is installed. ```typescript import { Liquid } from 'liquidjs'; const engine = new Liquid(); engine .parseAndRender('{{name | capitalize}}', {name: 'alice'}) .then(console.log); // outputs 'Alice' ``` -------------------------------- ### Limit Render Time with Large Loops Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/security-model.md This example demonstrates a loop that could potentially exceed render time limits. Use `renderLimit` to prevent such scenarios. ```liquid {%- for i in (1..10000000) -%} order: {{i}} {%- endfor -%} ``` -------------------------------- ### plugin(fn) Source: https://context7.com/harttle/liquidjs/llms.txt Installs a reusable plugin function. The plugin function receives the `Liquid` class as an argument, and `this` inside the function refers to the engine instance. ```APIDOC ## `plugin(fn)` — Install a Plugin Loads a reusable plugin. A plugin is a function receiving the `Liquid` class; `this` inside the function refers to the engine instance. ```javascript // upup-plugin.js module.exports = function upupPlugin (Liquid) { this.registerFilter('upup', value => String(value).toUpperCase()) this.registerFilter('shout', (value, times = 1) => String(value).toUpperCase() + '!'.repeat(times) ) } // main.js const { Liquid } = require('liquidjs') const engine = new Liquid() engine.plugin(require('./upup-plugin')) const result = await engine.parseAndRender( '{{ greeting | upup }} | {{ greeting | shout: 3 }}', { greeting: 'hello' } ) console.log(result) // => "HELLO | HELLO!!!" ``` ``` -------------------------------- ### Jekyll-like Include Syntax Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/options.md Example of using Jekyll-like include syntax, which changes parameter separation and variable referencing. This enables static filenames and uses '=' for parameters. ```liquid // entry template {% include article.html header="HEADER" content="CONTENT" %} // article.html
{{include.header}}
{{include.content}}
``` -------------------------------- ### Modulo Filter with Integers Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/modulo.md Demonstrates the modulo filter with integer division. Use this filter to get the remainder of a division. ```liquid {{ 3 | modulo: 2 }} ``` ```text 1 ``` ```liquid {{ 24 | modulo: 7 }} ``` ```text 3 ``` -------------------------------- ### Configure LiquidJS Engine Instance Source: https://context7.com/harttle/liquidjs/llms.txt Create a new LiquidJS engine instance with custom options for template resolution, caching, and output escaping. This example demonstrates setting up paths, extensions, and global variables. ```javascript const path = require('path') const { Liquid } = require('liquidjs') const engine = new Liquid({ root: [ path.resolve(__dirname, 'views'), path.resolve(__dirname, 'views/partials') ], partials: path.resolve(__dirname, 'views/partials'), layouts: path.resolve(__dirname, 'views/layouts'), extname: '.liquid', // auto-append extension on file lookups cache: process.env.NODE_ENV === 'production', // cache parsed templates strictVariables: false, // undefined vars render as '' strictFilters: false, // unknown filters silently skipped jsTruthy: false, // use Liquid truthiness (only false/nil are falsy) trimTagRight: false, // don't strip whitespace after tags outputEscape: 'escape', // auto-HTML-escape all {{ output }} globals: { siteName: 'My App' } // available in every template }) // Basic render const html = await engine.parseAndRender( '{{ siteName }}: {{ page.title }}', { page: { title: 'Home' } } ) console.log(html) // => My App: Home ``` -------------------------------- ### Reject products by type Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/reject.md Use reject with a property name and a target value to exclude specific items. This example filters out products of type 'kitchen'. ```liquid {% assign non_kitchen_products = products | reject: "type", "kitchen" %} ``` -------------------------------- ### Custom file system implementation for LiquidJS Source: https://github.com/harttle/liquidjs/wiki/Render-a-File Provide a custom file system implementation to the Liquid constructor to define how templates are fetched. This example shows reading templates from a database. ```javascript var engine = new Liquid({ fs: { readFileSync (file) { return db.model('Template').findByIdSync(file).text }, await readFile (file) { const template = await db.model('Template').findById(file) return template.text }, existsSync () { return true }, await exists () { return true }, resolve(root, file, ext) { return file } } }); ``` -------------------------------- ### Using unshift to add an element to an array Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/unshift.md This example demonstrates how to use the `unshift` filter to add 'apples' to the front 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 %} ``` -------------------------------- ### Render Templates with Express Source: https://github.com/harttle/liquidjs/wiki/Use-with-Expressjs Examples of rendering 'hello.liquid' and 'world.liquid' templates using Express's res.render method, assuming they are located in directories configured via LiquidJS root and Express views options. ```javascript res.render('hello') res.render('world') ``` -------------------------------- ### Table Row with Offset Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tags/tablerow.md Starts the tablerow loop after a specific index using the `offset` parameter. This allows skipping initial items in a collection. ```liquid {% tablerow product in collection.products cols:2 offset:3 %} {{ product.title }} {% endtablerow %} ``` -------------------------------- ### Map categories without compact Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/compact.md This example demonstrates mapping the 'category' attribute from a list of pages. Without `compact`, `nil` values appear in the output for pages missing the 'category' attribute. ```liquid {% assign site_categories = site.pages | map: "category" %} {% for category in site_categories %} - {{ category }} {% endfor %} ``` -------------------------------- ### LiquidJS Repeat Tag Example Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/render-tag-content.md This Liquid template demonstrates the usage of a custom 'repeat' tag, which renders its content multiple times. It also shows how to access context variables like 'repeat.i'. ```liquid {% repeat %} {{ repeat.i }}. {{ "hello world!" | capitalize }} {% endrepeat %} ``` -------------------------------- ### Basic Unless Condition Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tags/unless.md Use the unless tag to render content when a condition is false. This example shows rendering text if the product title is not 'Awesome Shoes'. ```liquid {% unless product.title == "Awesome Shoes" %} These shoes are not awesome. {% endunless %} ``` -------------------------------- ### Using uniq filter Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/uniq.md This example demonstrates how to use the `uniq` filter to remove duplicate elements from an array. The input array is created by splitting a string, and the output is joined back into a string. ```liquid {% assign my_array = "ants, bugs, bees, bugs, ants" | split: ", " %} {{ my_array | uniq | join: ", " }} ``` -------------------------------- ### Limit Memory Usage with Exponential Growth Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/security-model.md This example shows how array concatenation within a loop can lead to exponential memory growth. `memoryLimit` helps to control this by counting LiquidJS's internal memory allocations. ```liquid {% assign array = "1,2,3" | split: "," %} {% for i in (1..32) %} {% assign array = array | concat: array %} {% endfor %} ``` -------------------------------- ### Build Documentation Site Source: https://github.com/harttle/liquidjs/blob/master/CONTRIBUTING.md Build the documentation site, which includes the playground. ```bash npm run build:docs ``` -------------------------------- ### Get Array Length with Size Filter Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/size.md The size filter can also be used on arrays to determine the number of elements. This example shows how to get the size of an array created with the split filter. ```liquid {% assign my_array = "apples, oranges, peaches, plums" | split: ", " %} {{ my_array.size }} ``` -------------------------------- ### Build and Test Project Source: https://github.com/harttle/liquidjs/blob/master/CONTRIBUTING.md Run these commands to build the project and execute tests. Tests require a prior build. ```bash npm run build npm run test ``` -------------------------------- ### Custom Block Tag Implementation for Static Analysis Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/static-analysis.md This example shows how to implement a custom block tag in LiquidJS, including methods required for static analysis. Ensure the tag implements `children()`, `blockScope()`, and `arguments()` as needed. ```javascript import { Liquid, Tag, Hash } from 'liquidjs' class ExampleTag extends Tag { args templates constructor (token, remainTokens, liquid, parser) { super(token, remainTokens, liquid) this.args = new Hash(token.tokenizer) this.templates = [] const stream = parser.parseStream(remainTokens) .on('tag:endexample', () => { stream.stop() }) .on('template', (tpl) => this.templates.push(tpl)) .on('end', () => { throw new Error(`tag ${token.getText()} not closed`) }) stream.start() } * render (ctx, emitter) { const scope = (yield this.args.render(ctx)) ctx.push(scope) yield this.liquid.renderer.renderTemplates(this.templates, ctx, emitter) ctx.pop() } * children () { return this.templates } * arguments () { yield * Object.values(this.args.hash).filter((el) => el !== undefined) } blockScope () { return Object.keys(this.args.hash) } } ``` -------------------------------- ### Access First Item with Dot Notation Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/first.md When using `first` within tags, dot notation provides a cleaner syntax. This example shows accessing the first element of an array assigned to a variable. ```liquid {% assign my_array = "zebra, octopus, giraffe, tiger" | split: ", " %} {{ my_array.first }} ``` -------------------------------- ### Get Segmented Variable Paths from Template Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/static-analysis.md Use `Liquid.variableSegments` to get an array of strings and numbers that make up each variable's path. This method is asynchronous. ```javascript // continued from above engine.variableSegments(template).then(console.log) ``` -------------------------------- ### Find Index of First Matching Element Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/find_index_exp.md This example demonstrates how to use the find_index_exp filter to find the index of the first member in an array whose graduation year is 2014. The filter takes the current item as the first argument and the expression to evaluate as the second. ```javascript const members = [ { graduation_year: 2013, name: 'Jay' }, { graduation_year: 2014, name: 'John' }, { graduation_year: 2014, name: 'Jack' } ] ``` ```liquid {{ members | find_index_exp: "item", "item.graduation_year == 2014" | json }} ``` -------------------------------- ### Get Global Variable Segments from Template Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/static-analysis.md Use `Liquid.globalVariableSegments` to get variable paths excluding those typically defined by template authors (e.g., from `{% assign %}` or `{% for %}`). This method is asynchronous. ```javascript // continued from above engine.globalVariableSegments(template).then(console.log) ``` -------------------------------- ### Initialize and Render Liquid.js in Browser Source: https://github.com/harttle/liquidjs/blob/master/demo/browser/index.html Instantiate the Liquid.js engine and render a template with a given context. Ensure the Liquid object is available globally. ```javascript var Liquid = window.liquidjs.Liquid var engine = new Liquid({ extname: '.html', cache: true }) var src = "

Welcome to {{ name | capitalize}}, {% include 'date.html' %}

" var ctx = { name: 'Liquid', date: new Date() } engine.parseAndRender(src, ctx) .then(function(html) { document.body.innerHTML = html }) ``` -------------------------------- ### Render Template from CLI (File) Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/setup.md Render a Liquid template by specifying its path using the '@' prefix. ```bash npx liquidjs --template @./some-template.liquid ``` -------------------------------- ### Get Distinct Variables from Template Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/static-analysis.md Use `Liquid.variablesSync` 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)) ``` -------------------------------- ### Render Partials with Arguments Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/partials-and-layouts.md Demonstrates rendering a partial multiple times with different arguments. The `.liquid` extension can be omitted if configured. ```liquid // file: color.liquid color: '{{ color }}' shape: '{{ shape }}' ``` ```liquid // file: theme.liquid {% assign shape = 'circle' %} {% render 'color.liquid' %} {% render 'color.liquid' with 'red' %} {% render 'color.liquid', color: 'yellow', shape: 'square' %} ``` -------------------------------- ### Get last item of a string split into an array Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/last.md Use the `last` filter after splitting a string by a delimiter to get the last word or segment. This is useful for extracting specific parts of text. ```liquid {{ "Ground control to Major Tom." | split: " " | last }} ``` -------------------------------- ### Get Current Date and Time Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/date.md Use the special keywords 'now' or 'today' as input to the date filter to get the current date and time. Note that this reflects the time of page generation, not the user's current time. ```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 ``` -------------------------------- ### Initialize LiquidJS with Cache Option Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/options.md Demonstrates initializing LiquidJS with the cache option enabled for performance improvement. The cache option defaults to false. ```javascript const { Liquid } = require('liquidjs') const engine = new Liquid({ cache: true }) ``` -------------------------------- ### Slice String by Index and Length Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/slice.md Extracts a substring starting from a specified index with a given length. ```liquid {{ "Liquid" | slice: 2, 5 }} ``` -------------------------------- ### Basic Layout Usage Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tags/layout.md 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 ``` -------------------------------- ### Render Template from CLI Source: https://github.com/harttle/liquidjs/wiki/Home Use the npx command to render a Liquid template directly from the command line. ```bash echo '{{"hello" | capitalize}}' | npx liquidjs ``` -------------------------------- ### Define Range for Iteration Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tags/for.md Loops through a sequence of numbers defined by a start and end point, which can be literals or variables. ```liquid {% for i in (3..5) %} {{- i -}} {% endfor-%} {% assign num = 4 %} {% for i in (1..num) %} {{- i -}} {% endfor %} ``` -------------------------------- ### Custom Delimiters for Tags and Filters Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/options.md Customize delimiters to avoid conflicts with other languages. This example uses `<%=` and `%>` for output delimiters. ```ejs <%= username | append: ", welcome to LiquidJS!" %> ``` -------------------------------- ### Basic Template Rendering with Liquid.js Source: https://github.com/harttle/liquidjs/wiki/Home Initialize the Liquid.js engine and render a simple template with a given context. Requires the 'liquidjs' module. ```javascript var { Liquid } = require('liquidjs'); var engine = new Liquid(); engine .parseAndRender('{{name | capitalize}}', {name: 'alice'}) .then(console.log); // outputs 'Alice' ``` -------------------------------- ### `renderFile(file, scope, options?)` Source: https://context7.com/harttle/liquidjs/llms.txt Reads and renders a template file from the configured `root` directories. The file extension is appended automatically when `extname` is set. ```APIDOC ## `renderFile(file, scope, options?)` — Render a Template File Reads and renders a template file from the configured `root` directories. The file extension is appended automatically when `extname` is set. ```javascript const path = require('path') const { Liquid } = require('liquidjs') const engine = new Liquid({ root: path.resolve(__dirname, 'views'), extname: '.liquid' }) // views/product.liquid: //

{{ product.title }}

//

Price: ${{ product.price | round: 2 }}

// {% render "badge", label: product.badge %} const html = await engine.renderFile('product', { product: { title: 'Widget Pro', price: 29.995, badge: 'new' } }) console.log(html) //

Widget Pro

//

Price: $30

// new // Multiple root directories for fallback lookup const multiRoot = new Liquid({ root: ['views/overrides', 'views/defaults'], extname: '.html' }) await multiRoot.renderFile('header', { user: 'Bob' }) ``` ``` -------------------------------- ### Get Full Variable Paths from Template Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/static-analysis.md Use `Liquid.fullVariables` to retrieve a list of variables including their properties as strings. This method is asynchronous. ```javascript // continued from above engine.fullVariables(template).then(console.log) ``` -------------------------------- ### Custom Abstract File System Implementation Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/render-file.md Implement a custom file system by providing an object with methods like `readFileSync`, `readFile`, `existsSync`, `exists`, `contains`, and `resolve` to the `fs` option. This allows fetching templates from sources other than the file system, such as 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 } } }); ``` -------------------------------- ### Render Template from CLI (Inline) Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/setup.md Use npx to render a Liquid template directly from the command line by providing the template inline. ```bash npx liquidjs --template '{{"hello" | capitalize}}' ``` -------------------------------- ### Decode Base64 String Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/base64_decode.md Use the base64_decode filter to convert a Base64 encoded string to its original text. This example decodes a simple string. ```liquid {{ "b25lIHR3byB0aHJlZQ==" | base64_decode }} ``` -------------------------------- ### Pop an element from an array Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/pop.md Use the pop filter to get a new array with the last element removed. The original array remains unchanged. ```liquid {% assign fruits = "apples, oranges, peaches" | split: ", " %} {% assign everything = fruits | pop %} {% for item in everything %} - {{ item }} {% endfor %} ``` -------------------------------- ### Create and Push Branch Source: https://github.com/harttle/liquidjs/blob/master/CONTRIBUTING.md Commands to create a new branch, stage changes, commit, and push to your fork. ```bash git switch -c your_branch_name git add . git commit -m "feat: Adding my change" git push ``` -------------------------------- ### Get Absolute Value of Positive Number Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/abs.md Applying the abs filter to a positive number returns the number itself. It ensures the output is always non-negative. ```liquid {{ 4 | abs }} ``` -------------------------------- ### Wrap Content in a Div Tag Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/render-tag-content.md Example of a Liquid tag that wraps its content within a div element. This demonstrates basic tag content rendering. ```liquid {% wrap %} {{ "hello world!" | capitalize }} {% endwrap %} ``` -------------------------------- ### Reverse Array Elements Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/reverse.md Use the reverse filter to reverse 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: ", " }} ``` -------------------------------- ### Get String Length with Size Filter Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/size.md Use the size filter to count the number of characters in a string. This is useful for displaying character limits or lengths. ```liquid {{ "Ground control to Major Tom." | size }} ``` -------------------------------- ### Get Absolute Value of Number as String Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/abs.md The abs filter can also process strings that contain only a numeric value, converting them to their absolute numeric representation. ```liquid {{ "-19.86" | abs }} ``` -------------------------------- ### Specify Output File from CLI Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/setup.md Direct the rendered output to a specified file instead of stdout. ```bash npx liquidjs --template '{{"hello" | capitalize}}' --output ./hello.txt ``` -------------------------------- ### Configure Multiple Template Roots Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/render-file.md When using multiple directories for templates, partials, and layouts, provide an array of paths to the respective options. Templates will be looked up in the order they appear in the arrays. ```javascript var engine = new Liquid({ root: ['views/'], partials: ['views/partials/'], layouts: ['views/layouts/'], extname: '.liquid' }); ``` -------------------------------- ### Layout Templates with Blocks Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/partials-and-layouts.md Illustrates template inheritance using layout files. A child template can override content blocks defined in a parent layout. ```liquid // file: default-layout.liquid Header {% block content %}My default content{% endblock %} Footer ``` ```liquid // file: page.liquid {% layout "default-layout.liquid" %} {% block content %}My page content{% endblock %} ``` -------------------------------- ### Jekyll Included Template Content - LiquidJS Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tags/include.md Example of an 'article.html' partial template using Jekyll include syntax, where parameters are accessed via the 'include' variable. ```html
{{include.header}}
{{include.content}}
``` -------------------------------- ### Pass Context from CLI (File) Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/setup.md Load context data from a JSON file by specifying its path with the '@' prefix. ```bash npx liquidjs --template 'Hello, {{ name }}!' --context @./some-context.json ``` -------------------------------- ### Use a Plugin with Liquid.js Engine Source: https://github.com/harttle/liquidjs/wiki/Plugins Instantiate the Liquid engine and then use the `.plugin()` method to register your custom plugin. After registration, you can use the plugin's filters or tags in your templates. ```javascript const engine = new Liquid() engine.plugin(require('./upup.js')); engine .parseAndRender('{{ "foo" | upup }}') .then(console.log) // outputs "FOO" ``` -------------------------------- ### Render Template from CLI (stdin) Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/setup.md Pipe the Liquid template content to the CLI command using '@-' to read from stdin. ```bash echo '{{"hello" | capitalize}}' | npx liquidjs --template @- ``` -------------------------------- ### Get Absolute Value of Negative Number Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/abs.md Use the abs filter to convert a negative number to its positive equivalent. This filter works directly on numeric types. ```liquid {{ -17 | abs }} ``` -------------------------------- ### new Liquid(options) Source: https://context7.com/harttle/liquidjs/llms.txt Creates a new LiquidJS engine instance. Options can be provided to configure aspects like template roots, partials, layouts, file extensions, caching, strictness of variables and filters, truthiness, whitespace trimming, output escaping, and global variables. ```APIDOC ## new Liquid(options) - Engine Constructor Creates a new LiquidJS engine instance. All options are optional; sensible defaults apply (e.g., `root: ['.']`, `extname: ''`, no caching, Liquid-compatible truthiness). ```javascript const path = require('path') const { Liquid } = require('liquidjs') const engine = new Liquid({ root: [ path.resolve(__dirname, 'views'), path.resolve(__dirname, 'views/partials') ], partials: path.resolve(__dirname, 'views/partials'), layouts: path.resolve(__dirname, 'views/layouts'), extname: '.liquid', // auto-append extension on file lookups cache: process.env.NODE_ENV === 'production', // cache parsed templates strictVariables: false, // undefined vars render as '' strictFilters: false, // unknown filters silently skipped jsTruthy: false, // use Liquid truthiness (only false/nil are falsy) trimTagRight: false, // don't strip whitespace after tags outputEscape: 'escape', // auto-HTML-escape all {{ output }} globals: { siteName: 'My App' } // available in every template }) // Basic render const html = await engine.parseAndRender( '{{ siteName }}: {{ page.title }}', { page: { title: 'Home' } } ) console.log(html) // => My App: Home ``` ``` -------------------------------- ### Jekyll style reject for array matching Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/reject.md When `jekyllWhere` is enabled, the reject filter uses `Array.includes` for matching when the property is an array. This example excludes pages tagged with 'cat'. ```javascript const pages = [ { tags: ["cat", "food"], title: 'Cat Food' }, { tags: ["dog", "food"], title: 'Dog Food' }, ] ``` ```liquid {% assign selected = pages | reject: 'tags', "cat" %} ``` -------------------------------- ### Using the shift Filter on an Array Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/shift.md Demonstrates how to use the shift filter to remove the first element from an array. The original array remains unchanged. ```liquid {% assign fruits = "apples, oranges, peaches" | split: ", " %} {% assign everything = fruits | shift %} {% for item in everything %} - {{ item }} {% endfor %} ``` -------------------------------- ### Reject with nested property access Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/reject.md Property can be a Liquid variable expression, allowing for nested property access. This example rejects products where the nested 'class' property is 'B'. ```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" %} ``` -------------------------------- ### Reject products by truthy taxable property Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/reject.md When no target value is provided, reject excludes items where the specified property is truthy. This example filters out products that are marked as 'taxable'. ```liquid {% assign not_taxed_products = products | reject: "taxable" %} ``` -------------------------------- ### Check Project Status Source: https://github.com/harttle/liquidjs/blob/master/CONTRIBUTING.md Use this command to run build, tests, lint, and performance checks. It also validates commit message format. ```bash npm run check ``` -------------------------------- ### Get First Item of String Array Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/first.md Use the `first` filter after splitting a string into an array to retrieve the first element. This is useful for extracting the initial part of a text. ```liquid {{ "Ground control to Major Tom." | split: " " | first }} ``` -------------------------------- ### Configure Template Lookup with Root and Views Options Source: https://github.com/harttle/liquidjs/wiki/Use-with-Expressjs Demonstrates how to configure both LiquidJS's root option and Express's views option to manage template directories. This allows templates from both specified directories to be resolved and rendered. ```javascript var { Liquid } = require('liquidjs'); var engine = new Liquid({ root: './views1/' }); app.engine('liquid', engine.express()); app.set('views', './views2'); // specify the views directory app.set('view engine', 'liquid'); // set liquid to default ``` -------------------------------- ### Normalize Whitespace Example Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/normalize_whitespace.md Use this filter to collapse multiple whitespace characters (spaces, tabs, newlines) into a single space. This is useful for cleaning up user input or formatted text. ```liquid {{ "a \n b" | normalize_whitespace }} ``` -------------------------------- ### Layout Templates with Blocks in LiquidJS Source: https://github.com/harttle/liquidjs/wiki/Partials-and-Layouts Shows how to define a default layout with a content block and how to extend this layout in a page template, overriding the content block. ```liquid // file: default-layout.liquid Header {% block content %}My default content{% endblock %} Footer ``` ```liquid // file: page.liquid {% layout "default-layout" %} {% block content %}My page content{% endblock %} ``` -------------------------------- ### Basic Cycle Usage Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tags/cycle.md Use this for simple alternating values. Each call to `cycle` advances to the next item in the list. ```liquid {% cycle "one", "two", "three" %} {% cycle "one", "two", "three" %} {% cycle "one", "two", "three" %} {% cycle "one", "two", "three" %} ``` -------------------------------- ### Basic Usage of escape_once Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/escape_once.md Demonstrates how escape_once handles a simple string with characters that need escaping. It converts '<' to '<' and '&' to '&'. ```liquid {{ "1 < 2 & 3" | escape_once }} ``` -------------------------------- ### Add Inline Comments to Liquid Template Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tags/inline_comment.md Use the `{% # ... %}` tag to add inline comments. Text within these tags will not be rendered in the output. Each line of a multi-line 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 %} ``` -------------------------------- ### Render String Template Asynchronously Source: https://context7.com/harttle/liquidjs/llms.txt Parse and render a Liquid template string against a scope object in a single asynchronous call. This example shows the use of tags like `assign`, `if`, and `for` with filters. ```javascript const { Liquid } = require('liquidjs') const engine = new Liquid() // Outputs, filters, and tags all work together const result = await engine.parseAndRender(` {% assign items = cart.products %} {% if items.size > 0 %} {% else %}

Your cart is empty.

{% endif %} `.trim(), { cart: { products: [ { name: 'apple', price: 1.999 }, { name: 'banana', price: 0.5 }, { name: 'cherry', price: 3.1 }, { name: 'date', price: 4.0 } ] } }) console.log(result) // ``` -------------------------------- ### Render Template with JSON Context via CLI Source: https://github.com/harttle/liquidjs/wiki/Home Pipe a template string to npx liquidjs and provide a JSON string as the context for rendering. ```bash echo 'Hello, {{ name }}' | npx liquidjs '{"name": "Snake"}' ``` -------------------------------- ### Modulo Filter with Floating-Point Numbers Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/modulo.md Demonstrates the modulo filter with floating-point division. Note the potential for floating-point inaccuracies in the result. ```liquid {{ 183.357 | modulo: 12 }} ``` ```text 3.3569999999999993 ``` -------------------------------- ### Configure template root with multiple directories Source: https://github.com/harttle/liquidjs/wiki/Render-a-File When the root option is a list of directories, LiquidJS will look up templates in the specified order. The first existing file found will be used. ```javascript var engine = new Liquid({ // relative paths will be resolved against `pwd` root: ['views/', 'views/partials/'], extname: '.liquid' }); ``` -------------------------------- ### Decode Base64 String with Special Characters Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/base64_decode.md This example demonstrates decoding a Base64 string that includes special characters, showing the filter's ability to handle various character sets. ```liquid {{ "SGVsbG8sIFdvcmxkISBAIyQl" | base64_decode }} ``` -------------------------------- ### Slugify with 'pretty' Mode Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/slugify.md Uses the 'pretty' mode for slugification, preserving spaces and specific non-alphanumeric characters like . _ ~ ! $ & ' ( ) + , ; @. ```liquid {{ "The _config.yml file" | slugify: "pretty" }} ``` -------------------------------- ### Render Template File with LiquidJS Source: https://context7.com/harttle/liquidjs/llms.txt Reads and renders a template file from configured root directories. The file extension is appended automatically if `extname` is set. Supports multiple root directories for fallback lookup. ```javascript const path = require('path') const { Liquid } = require('liquidjs') const engine = new Liquid({ root: path.resolve(__dirname, 'views'), extname: '.liquid' }) // views/product.liquid: //

{{ product.title }}

//

Price: ${{ product.price | round: 2 }}

// {% render "badge", label: product.badge %} const html = await engine.renderFile('product', { product: { title: 'Widget Pro', price: 29.995, badge: 'new' } }) console.log(html) //

Widget Pro

//

Price: $30

// new // Multiple root directories for fallback lookup const multiRoot = new Liquid({ root: ['views/overrides', 'views/defaults'], extname: '.html' }) await multiRoot.renderFile('header', { user: 'Bob' }) ``` -------------------------------- ### Render a specific file with LiquidJS Source: https://github.com/harttle/liquidjs/wiki/Render-a-File Configure the Liquid engine with a root directory for templates and an extension name. Then, use renderFile to process a template by its name, passing in any necessary data. ```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" ``` -------------------------------- ### Render String Template Synchronously Source: https://context7.com/harttle/liquidjs/llms.txt Synchronously parse and render a Liquid template string. This is useful when asynchronous operations are inconvenient. Includes an example of error handling for undefined variables when `strictVariables` is enabled. ```javascript const { Liquid } = require('liquidjs') const engine = new Liquid() const output = engine.parseAndRenderSync( '{{ greeting | append: ", " | append: name | append: "!" }}', { greeting: 'Hello', name: 'Alice' } ) console.log(output) // => "Hello, Alice!" // Error handling try { const strict = new Liquid({ strictVariables: true }) strict.parseAndRenderSync('{{ missing }}', {}) } catch (e) { console.error(e.message) // => "undefined variable: missing" } ``` -------------------------------- ### Use `liquid` tag for concise logic Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tags/liquid.md Encloses multiple tags within one set of delimiters to write Liquid logic more concisely. Use this when you have several Liquid tags that can be grouped together for better readability. ```liquid {% liquid assign names = 'Bob, Sally' | split: ', ' for name in names echo 'Hello, ' | append: name unless forloop.last echo ', ' endunless endfor %} ``` -------------------------------- ### express() Source: https://context7.com/harttle/liquidjs/llms.txt Provides a view engine callback compatible with Express.js's `app.engine()` method. It merges the `root` option with Express's `views` setting for template lookup. ```APIDOC ## `express()` — Express.js View Engine Integration Returns a view engine callback compatible with Express's `app.engine()`. The `root` option and Express's `views` setting are merged for template lookup. ```javascript const express = require('express') const path = require('path') const { Liquid } = require('liquidjs') const app = express() const engine = new Liquid({ root: path.resolve(__dirname, 'views'), extname: '.liquid', cache: process.env.NODE_ENV === 'production' }) app.engine('liquid', engine.express()) app.set('views', path.resolve(__dirname, 'views')) app.set('view engine', 'liquid') app.get('/', (req, res) => { res.render('index', { title: 'Home', user: { name: 'Alice', role: 'admin' }, items: ['Apple', 'Banana', 'Cherry'] }) }) app.listen(3000, () => console.log('Server running on port 3000')) ``` ``` -------------------------------- ### LiquidJS Case Statement Example Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tags/case.md Use the case tag to compare a variable against multiple values. The `when` tag can handle multiple comma-separated values for a single condition. An `else` block can be used for unmatched values. ```liquid {% assign handle = "cake" %} {% case handle %} {% when "cake" %} This is a cake {% when "cookie", "biscuit" %} This is a cookie {% else %} This is neither a cake nor a cookie {% endcase %} ``` -------------------------------- ### Include LiquidJS in Browsers Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tutorials/setup.md Load LiquidJS in the browser using UMD bundles from a CDN. Use the minified version for production and the unminified for development. ```html ``` -------------------------------- ### Check for Performance Regressions Source: https://github.com/harttle/liquidjs/blob/master/CONTRIBUTING.md Compare current performance against the latest 'liquidjs' version to detect regressions. ```bash npm run perf:diff ``` -------------------------------- ### Render with 'with' Parameter Source: https://github.com/harttle/liquidjs/blob/master/docs/source/tags/render.md Pass a single object to a snippet using the 'with...as' syntax. The variable specified after 'as' will hold the object's value within the partial template. ```liquid {% assign featured_product = all_products['product_handle'] %} {% render 'product' with featured_product as product %} ``` -------------------------------- ### Find Index of Array Element by Attribute Source: https://github.com/harttle/liquidjs/blob/master/docs/source/filters/find_index.md Use the find_index filter to get the 0-based index of the first object in an array where a specified attribute matches a given value. Returns nil if no matching element is found. Requires the array to be defined in the Liquid context. ```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 }} ```