### 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
{% 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: //
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) //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. ```htmlYour 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) //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) //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 }} ```