mirror of
https://github.com/harttle/liquidjs.git
synced 2026-09-15 12:20:40 -07:00
docs: highlight npx in bash blocks and polish English copy
Use Prism insertBefore for CLI commands like npx, tighten tutorial and reference wording, and keep YAML titles free of backticks so sidebar and page headings stay correct. Co-authored-by: Cursor <[email protected]>
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
title: Access Scope in Filters
|
||||
---
|
||||
|
||||
As covered in [Register Filters/Tags][register-filters], we can access filter arguments directly in filter function like:
|
||||
As covered in [Register Filters/Tags][register-filters], we can access filter arguments directly in a filter function like:
|
||||
|
||||
```javascript
|
||||
// Usage: {{ 1 | add: 2, 3 }}
|
||||
@@ -10,7 +10,7 @@ As covered in [Register Filters/Tags][register-filters], we can access filter ar
|
||||
engine.registerFilter('add', (initial, arg1, arg2) => initial + arg1 + arg2)
|
||||
```
|
||||
|
||||
When it comes to stateful filters, for example transform a URL path to full URL, we'll need to access a `origin` in current scope:
|
||||
When it comes to stateful filters, for example transforming a URL path to a full URL, we'll need to access an `origin` in the current scope:
|
||||
|
||||
```javascript
|
||||
// Usage: {{ '/index.html' | fullURL }}
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
title: Caching
|
||||
---
|
||||
|
||||
In a typical website project, we'll have a directory of view templates and they'll be rendered multiple times. In production environment the template files are not likely to be changed over time (other than re-deployments). Thus it makes sense to cache the file contents and the parsed templates (in a kind of AST) to improve performance.
|
||||
In a typical website project, we'll have a directory of view templates and they'll be rendered multiple times. In a production environment the template files are not likely to change over time (other than re-deployments). Thus it makes sense to cache the file contents and the parsed templates (in a kind of AST) to improve performance.
|
||||
|
||||
LiquidJS provides multiple ways to cache the parsed templates to improve performance.
|
||||
|
||||
## Programmatically
|
||||
|
||||
The [.parse()][parse], [.parseFile()][parseFile], [.parseFileSync()][parseFileSync] APIs are used to parse templates from string or files. The result template can be then rendered multiple times with different context.
|
||||
The [.parse()][parse], [.parseFile()][parseFile], [.parseFileSync()][parseFileSync] APIs are used to parse templates from strings or files. The resulting template can then be rendered multiple times with different context.
|
||||
|
||||
Parse from string:
|
||||
|
||||
|
||||
@@ -16,11 +16,11 @@ Getting started and building is described in [CONTRIBUTING.md](https://github.co
|
||||
|
||||
**Commit Message**: Please align to [the Angular Commit Message Guidelines](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#commits), especially note the [type identifier](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#type), on which semantic-release bot depends.
|
||||
|
||||
**Backward-Compatibility**: please be backward-compatible. LiquidJS is used by multiple layers of softwares, including underlying libraries, compilers, site generators and Web servers. It's not easy to do a major upgrade for most of them.
|
||||
**Backward-Compatibility**: please be backward-compatible. LiquidJS is used by multiple layers of software, including underlying libraries, compilers, site generators and Web servers. It's not easy to do a major upgrade for most of them.
|
||||
|
||||
## Financial Support
|
||||
|
||||
LiquidJS is Open Source and Free. To help it live and thrive, especially when LiquidJS is benefiting your business, please consider contribute on [GitHub Sponsors](https://github.com/sponsors/harttle) or [Open Collective][oc].
|
||||
LiquidJS is Open Source and Free. To help it live and thrive, especially when LiquidJS is benefiting your business, consider contributing on [GitHub Sponsors](https://github.com/sponsors/harttle) or [Open Collective][oc].
|
||||
|
||||
I'll add all financial contributors into [README.md](https://github.com/harttle/liquidjs#financial-support) and it'll be also shown on https://liquidjs.com after next GitHub Actions build.
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ title: Differences with Shopify/liquid
|
||||
|
||||
## Compatibility
|
||||
|
||||
Being compatible with the Ruby version is one of our priorities. Liquid language is originally [implemented in Ruby][ruby-liquid] and used by Shopify and Jekyll (and thus GitHub Pages). As you can see it's one of the most popular template engines in Ruby. There're lots of people using LiquidJS to serve their templates originally written for Shopify themes and Jekyll sites.
|
||||
Being compatible with the Ruby version is one of our priorities. Liquid language is originally [implemented in Ruby][ruby-liquid] and used by Shopify and Jekyll (and thus GitHub Pages). As you can see it's one of the most popular template engines in Ruby. There are lots of people using LiquidJS to serve their templates originally written for Shopify themes and Jekyll sites.
|
||||
|
||||
So "being compatible" means serving developers from Shopify and Jekyll well:
|
||||
|
||||
@@ -13,8 +13,8 @@ So "being compatible" means serving developers from Shopify and Jekyll well:
|
||||
|
||||
In the meantime, it's now implemented in JavaScript, that means it has to be more powerful:
|
||||
|
||||
* **Async as first-class citizen**. Filters and tags can be implemented asynchronously by return a `Promise`.
|
||||
* **Also can be sync**. For scenarios that are not I/O intensive, render synchronously can be much faster. You can call synchronous APIs like `.renderSync()` as long as all the filters and tags in template support to be rendered synchronously. All builtin filters/tags support both sync and async render.
|
||||
* **Async as a first-class citizen**. Filters and tags can be implemented asynchronously by returning a `Promise`.
|
||||
* **Can also be synchronous**. For scenarios that are not I/O intensive, rendering synchronously can be much faster. You can call synchronous APIs like `.renderSync()` as long as all the filters and tags in the template can be rendered synchronously. All built-in filters/tags support both sync and async render.
|
||||
* **[Abstract file system][afs]**. Along with async feature, LiquidJS can be used to serve templates stored in Databases [#414][#414], on remote HTTP server [#485][#485], and so on.
|
||||
* **Additional tags and filters** like `layout` and `json`, `inspect`, `where_exp`, `group_by`, etc., see below for details.
|
||||
|
||||
|
||||
@@ -95,7 +95,7 @@ engine.parseAndRender("{{color}}", context).then(html => console.log(html))
|
||||
|
||||
## toLiquid
|
||||
|
||||
`toLiquid()` is not a method of `Drop`, but it can be used to return a `Drop`. In cases where you have a fixed structure in the `context` that cannot change its values, you can implement `toLiquid()` to let LiquidJS use the returned value instead of itself to render the templates.
|
||||
`toLiquid()` is not a method of `Drop`, but it can be used to return a `Drop`. In cases where you have a fixed structure in the `context` that cannot change its values, you can implement `toLiquid()` to let LiquidJS use the returned value instead of the object itself when rendering templates.
|
||||
|
||||
```javascript
|
||||
import { Liquid, Drop } from 'liquidjs'
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
title: Escaping
|
||||
---
|
||||
|
||||
Escaping is important in all languages, including LiquidJS. While escaping has 2 different meanings for a template engine:
|
||||
Escaping is important in all languages, including LiquidJS. Escaping has two different meanings for a template engine:
|
||||
|
||||
1. Escaping for the output, i.e. HTML escape. Used to escape HTML special characters so the output will not break HTML structures, aka HTML safe.
|
||||
2. Escaping for the language itself, i.e. Liquid escape. Used to output strings that's considered special in Liquid language. This will be useful when you're writing an article in Liquid template to introduce Liquid language.
|
||||
2. Escaping for the language itself, i.e. Liquid escape. Used to output strings that are considered special in the Liquid language. This is useful when you're writing an article in a Liquid template to introduce the Liquid language.
|
||||
|
||||
## HTML Escape
|
||||
|
||||
@@ -55,7 +55,7 @@ In LiquidJS, {{ this | escape }} will be HTML-escaped, but
|
||||
{{{ that }}} will not.
|
||||
```
|
||||
|
||||
Within strings literals in LiquidJS template, `\` can be used to escape special characters in string syntax. For example:
|
||||
Within string literals in a LiquidJS template, `\` can be used to escape special characters in string syntax. For example:
|
||||
|
||||
Input
|
||||
```liquid
|
||||
|
||||
@@ -5,7 +5,7 @@ describe: A short introduction to the Liquid template language and some simple d
|
||||
|
||||
LiquidJS is a simple, expressive and safe [Shopify][shopify/liquid] / GitHub Pages compatible template engine in pure JavaScript. The purpose of this repo is to provide a standard Liquid implementation for the JavaScript community. Liquid is originally implemented in Ruby and used by GitHub Pages, Jekyll and Shopify, see [Differences with Shopify/liquid][diff].
|
||||
|
||||
LiquidJS syntax is relatively simple. There're 2 types of markups in LiquidJS:
|
||||
LiquidJS syntax is relatively simple. There are 2 types of markups in LiquidJS:
|
||||
|
||||
- **Tags**. A tag consists of a tag name and optional arguments wrapped between `{%raw%}{%{%endraw%}` and `%}`.
|
||||
- **Outputs**. An output consists of a value and a list of filters, which is optional, wrapped between `{%raw%}{{{%endraw%}` and `}}`.
|
||||
@@ -38,7 +38,7 @@ A complete list of filters supported by LiquidJS can be found [here](../filters/
|
||||
|
||||
## Tags
|
||||
|
||||
**Tags** are used to control the template rendering process, manipulating template variables, inter-op with other templates, etc. For example `assign` can be used to define a variable which can be later used in the template:
|
||||
**Tags** are used to control the template rendering process, manipulating template variables, interacting with other templates, etc. For example `assign` can be used to define a variable that can be later used in the template:
|
||||
|
||||
```liquid
|
||||
{% assign foo = "FOO" %}
|
||||
@@ -50,7 +50,7 @@ Typically tags appear in pairs with a start tag and a corresponding end tag. For
|
||||
{% if foo == "FOO" %}
|
||||
Variable `foo` equals "FOO"
|
||||
{% else %}
|
||||
Variable `foo` not equals "FOO"
|
||||
Variable `foo` does not equal "FOO"
|
||||
{% endif %}
|
||||
```
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
title: Migrate to LiquidJS 9
|
||||
---
|
||||
|
||||
LiquidJS 9 has some fundamental improvements, including bugfixes, new features and performance improvement due to higher target(see #137). There're also some breaking changes.
|
||||
LiquidJS 9 has some fundamental improvements, including bugfixes, new features and performance improvements due to a higher target (see #137). There are also some breaking changes.
|
||||
|
||||
## Features
|
||||
|
||||
@@ -14,11 +14,11 @@ LiquidJS 9 has some fundamental improvements, including bugfixes, new features a
|
||||
* Rewrite boolean expression evaluation order, [#130](https://github.com/harttle/liquidjs/issues/130);
|
||||
* `break` and `continue` tags omitting output before them, [#123](https://github.com/harttle/liquidjs/issues/123);
|
||||
* Fixes errors in React.js demo during yarn install, [#145](https://github.com/harttle/liquidjs/issues/145);
|
||||
* Promise typed Drops are not await-ed some times.
|
||||
* Promise typed Drops are not always awaited.
|
||||
|
||||
## Performance
|
||||
|
||||
* Performance Improvements due to targeting to Node.js 8, see [#137](https://github.com/harttle/liquidjs/issues/137);
|
||||
* Performance Improvements due to targeting Node.js 8, see [#137](https://github.com/harttle/liquidjs/issues/137);
|
||||
* Memory footprint is reduced by 57.5%, see [#202](https://github.com/harttle/liquidjs/pull/202);
|
||||
* Render performance is improved by 100.3%, see [#205](https://github.com/harttle/liquidjs/pull/205).
|
||||
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
title: Operators
|
||||
---
|
||||
|
||||
LiquidJS operators are very simple and different. There're 2 types of operators supported:
|
||||
LiquidJS operators are very simple and different. There are 2 types of operators supported:
|
||||
|
||||
* Comparison operators: `==`, `!=`, `>`, `<`, `>=`, `<=`
|
||||
* Logic operators: `not`, `or`, `and`, `contains`
|
||||
* Logical operators: `not`, `or`, `and`, `contains`
|
||||
|
||||
Thus numerical operators are not supported and you cannot even plus two numbers like this `{% raw %}{{a + b}}{% endraw %}`, instead we need a filter `{% raw %}{{ a | plus: b}}{% endraw %}`. Actually `+` is a valid variable name in LiquidJS.
|
||||
Thus arithmetic operators are not supported and you cannot add two numbers like this `{% raw %}{{a + b}}{% endraw %}`. Instead, use a filter: `{% raw %}{{ a | plus: b}}{% endraw %}`. Actually `+` is a valid variable name in LiquidJS.
|
||||
|
||||
## Logic Operators
|
||||
## Logical Operators
|
||||
|
||||
### not
|
||||
|
||||
@@ -59,10 +59,10 @@ Input
|
||||
|
||||
1. Comparison operators, and `contains`. All comparison operators alongside `contains` have the same (highest) precedence.
|
||||
2. `not` operator. It has slightly more precedence than `or` and `and`.
|
||||
3. `or` and `and` operators. These logic operators have the same (lowest) precedence.
|
||||
3. `or` and `and` operators. These logical operators have the same (lowest) precedence.
|
||||
|
||||
## Associativity
|
||||
|
||||
Logic operators are evaluated from right to left, see [shopify docs][operator-order].
|
||||
Logical operators are evaluated from right to left, see [shopify docs][operator-order].
|
||||
|
||||
[operator-order]: https://shopify.dev/docs/api/liquid/basics#order-of-operations
|
||||
|
||||
@@ -11,27 +11,27 @@ const engine = new Liquid({
|
||||
})
|
||||
```
|
||||
|
||||
{% note info API Document %}
|
||||
Following is an overview for all the options, for exact types and signatures please refer to <a href="https://liquidjs.com/api/interfaces/LiquidOptions.html" target="_self">LiquidOptions | API</a>.
|
||||
{% note info API documentation %}
|
||||
Following is an overview for all the options. For exact types and signatures, see <a href="https://liquidjs.com/api/interfaces/LiquidOptions.html" target="_self">LiquidOptions | API</a>.
|
||||
{% endnote %}
|
||||
|
||||
## cache
|
||||
|
||||
**cache** is used to improve performance by caching previously parsed template structures, specially in cases when we're repeatedly parse or render files.
|
||||
**cache** is used to improve performance by caching previously parsed template structures, especially in cases when we repeatedly parse or render files.
|
||||
|
||||
It's default to `false`. When setting to `true` a default LRU cache of size 1024 will be enabled. And certainly it can be a number which indicates the size of cache you want.
|
||||
It defaults to `false`. When set to `true`, a default LRU cache of size 1024 will be enabled. It can also be a number indicating the cache size you want.
|
||||
|
||||
Additionally, it can also be a custom cache implementation. See [Caching][caching] for details.
|
||||
|
||||
## Partials/Layouts
|
||||
|
||||
**root** is used to specify template directories for LiquidJS to lookup and read template files. Can be a single string and an array of strings. See [Render Files][render-file] for details.
|
||||
**root** is used to specify template directories for LiquidJS to look up and read template files. Can be a single string or an array of strings. See [Render Files][render-file] for details.
|
||||
|
||||
**layouts** is used to specify template directories for LiquidJS to lookup files for `{% layout %}`. Same format as `root` and will default to `root` if not specified.
|
||||
**layouts** is used to specify template directories for LiquidJS to look up files for `{% layout %}`. Same format as `root` and will default to `root` if not specified.
|
||||
|
||||
**partials** is used to specify template directories for LiquidJS to lookup files for `{% render %}` and `{% include %}`. Same format as `root` and will default to `root` if not specified.
|
||||
**partials** is used to specify template directories for LiquidJS to look up files for `{% render %}` and `{% include %}`. Same format as `root` and will default to `root` if not specified.
|
||||
|
||||
**relativeReference** is set to `true` by default to allow relative filenames. Note that relatively referenced files are also need to be within corresponding root. For example you can reference another file like `{% render ../foo/bar %}` as long as `../foo/bar` is also within `partials` directory.
|
||||
**relativeReference** is set to `true` by default to allow relative filenames. Note that relatively referenced files also need to be within the corresponding root. For example you can reference another file like `{% render ../foo/bar %}` as long as `../foo/bar` is also within `partials` directory.
|
||||
|
||||
## dynamicPartials
|
||||
|
||||
@@ -62,7 +62,7 @@ LiquidJS defaults this option to <code>true</code> to be compatible with shopify
|
||||
- Use `=` instead of `:` to separate parameter key-values.
|
||||
- Parameters are under `include` variable instead of current scope.
|
||||
|
||||
For example in the following template, `name.html` is not quoted, `header` and `"HEADER"` are separated by `=`, and the `header` parameter is referenced by `include.header`. More details please check out [include][include].
|
||||
For example in the following template, `name.html` is not quoted, `header` and `"HEADER"` are separated by `=`, and the `header` parameter is referenced by `include.header`. For more details, see [include][include].
|
||||
|
||||
```liquid
|
||||
// entry template
|
||||
@@ -90,7 +90,7 @@ Before 2.0.1, <code>extname</code> is set to `.liquid` by default. To change tha
|
||||
|
||||
## fs
|
||||
|
||||
**fs** is used to define a custom file system implementation which will be used by LiquidJS to lookup and read template files. See [Abstract File System][abstract-fs] for details.
|
||||
**fs** is used to define a custom file system implementation which will be used by LiquidJS to look up and read template files. See [Abstract File System][abstract-fs] for details.
|
||||
|
||||
## globals
|
||||
|
||||
@@ -98,9 +98,9 @@ Before 2.0.1, <code>extname</code> is set to `.liquid` by default. To change tha
|
||||
|
||||
## jsTruthy
|
||||
|
||||
**jsTruthy** is used to use standard JavaScript truthiness rather than the Shopify.
|
||||
**jsTruthy** is used to use standard JavaScript truthiness rather than Shopify's.
|
||||
|
||||
it defaults to false. For example, when set to true, a blank string would evaluate to false with jsTruthy. With Shopify's truthiness, a blank string is true.
|
||||
It defaults to `false`. For example, when set to `true`, a blank string would evaluate to false with jsTruthy. With Shopify's truthiness, a blank string is true.
|
||||
|
||||
## outputEscape
|
||||
|
||||
@@ -108,13 +108,13 @@ it defaults to false. For example, when set to true, a blank string would evalu
|
||||
|
||||
- For untrusted output variables, set `outputEscape: "escape"` makes them be HTML escaped by default. You'll need [raw][raw] filter for direct output.
|
||||
- `"json"` is useful when you're using LiquidJS to create valid JSON files.
|
||||
- It can even be a function which allows you to control what variables are output throughout LiquidJS. Please note the input can be any type other than string, e.g. an filter returned an non-string value.
|
||||
- It can even be a function that allows you to control what variables are output throughout LiquidJS. Please note the input can be any type other than string, e.g. a filter may return a non-string value.
|
||||
|
||||
## Date
|
||||
|
||||
**timezoneOffset** is used to specify a different timezone to output dates, your local timezone will be used if not specified. For example, set `timezoneOffset: 0` to output all dates in UTC/GMT 00:00.
|
||||
|
||||
**preserveTimezones** is a boolean effects only literal timestamps. When set to `true`, all literal timestamps will remain the same when output. This is a parser option, so Date objects passed to LiquidJS as data will not be affected. Note that `preserveTimezones` has a higher priority than `timezoneOffset`.
|
||||
**preserveTimezones** is a boolean that affects only literal timestamps. When set to `true`, all literal timestamps will remain the same when output. This is a parser option, so Date objects passed to LiquidJS as data will not be affected. Note that `preserveTimezones` has a higher priority than `timezoneOffset`.
|
||||
|
||||
**dateFormat** is used to specify a default format to output dates. `%A, %B %-e, %Y at %-l:%M %P %z` will be used if not specified. For example, set `dateFormat: %Y-%m-%dT%H:%M:%S:%LZ` to output all dates in [JavaScript Date.toJson()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) format.
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ title: Parse Parameters
|
||||
|
||||
## Access Raw Parameters
|
||||
|
||||
As covered in [Register Filters/Tags][register-tags], tag parameters is available on `tagToken.args` as a raw string. For example:
|
||||
As covered in [Register Filters/Tags][register-tags], tag parameters are available on `tagToken.args` as a raw string. For example:
|
||||
|
||||
```javascript
|
||||
// Usage: {% random foo bar coo %}
|
||||
@@ -66,7 +66,7 @@ Async calls in LiquidJS are implemented by generators directly, for we can call
|
||||
|
||||
## Parse Key-Value Pairs as Named Parameters
|
||||
|
||||
Named parameters become very handy when there're optional parameters or lots of parameters, in which case the order of parameters is not important. This is exactly what [Hash][Hash] class is invented for.
|
||||
Named parameters become very handy when there are optional parameters or lots of parameters, in which case the order of parameters is not important. This is exactly what the [Hash][Hash] class was invented for.
|
||||
|
||||
```liquid
|
||||
{% random from:2, to:max %}
|
||||
|
||||
@@ -25,7 +25,7 @@ color: 'red' shape: 'circle'
|
||||
color: 'yellow' shape: 'square'
|
||||
```
|
||||
|
||||
More details please refer to the [render](../tags/render.html) tag.
|
||||
For more details, see the [render](../tags/render.html) tag.
|
||||
|
||||
{% note tip The ".liquid" Extension %}
|
||||
The ".liquid" extension in <code>layout</code>, <code>render</code> and <code>include</code> can be omitted if Liquid instance is created using `extname: ".liquid"` option. See <a href="./options.html#extname">the extname option</a> for details.
|
||||
@@ -54,4 +54,4 @@ My page content
|
||||
Footer
|
||||
```
|
||||
|
||||
More details please refer to the [layout](../tags/layout.html) tag.
|
||||
For more details, see the [layout](../tags/layout.html) tag.
|
||||
|
||||
@@ -6,9 +6,9 @@ A number of tags and filters can be encapsulated into a **plugin**, which will b
|
||||
|
||||
## Write a Plugin
|
||||
|
||||
A liquidjs plugin is simple function which takes the [Liquid class][liquid] as the first parameter and the Liquid instance for `this`. We can call liquidjs APIs on `this` to make certain changes, especially [register filters and tags][register].
|
||||
A LiquidJS plugin is a simple function that takes the [Liquid class][liquid] as the first parameter and uses the Liquid instance for `this`. We can call LiquidJS APIs on `this` to make certain changes, especially [register filters and tags][register].
|
||||
|
||||
Now we'll make a plugin to upper case every letter of the input, save the following snippet to `upup.js`:
|
||||
Now we'll make a plugin to uppercase every letter of the input. Save the following snippet to `upup.js`:
|
||||
|
||||
```javascript
|
||||
/**
|
||||
|
||||
@@ -62,7 +62,7 @@ See existing filter implementations here: <https://github.com/harttle/liquidjs/t
|
||||
|
||||
## Unregister Tags/Filters
|
||||
|
||||
In some cases it's desirable to disable some tags/filters (see [#324](https://github.com/harttle/liquidjs/issues/324)), you'll need to register a dummy tag/filter in which an corresponding Error throws.
|
||||
In some cases it's desirable to disable some tags/filters (see [#324](https://github.com/harttle/liquidjs/issues/324)). You'll need to register a dummy tag/filter that throws a corresponding Error.
|
||||
|
||||
```javascript
|
||||
// disable a tag
|
||||
|
||||
@@ -38,7 +38,7 @@ name: alice
|
||||
|
||||
## Template Lookup
|
||||
|
||||
Template files names passed to [renderFile][renderFile], [parseFile][parseFile], [renderFileSync][renderFileSync], [parseFileSync][parseFileSync] APIs,
|
||||
Template file names passed to [renderFile][renderFile], [parseFile][parseFile], [renderFileSync][renderFileSync], [parseFileSync][parseFileSync] APIs,
|
||||
and [include][include], [layout][layout] tags are resolved against [the root option][root].
|
||||
|
||||
It can be a string-typed path (see above example), or a list of root directories, in which case templates will be looked up in that order. e.g.
|
||||
@@ -96,7 +96,7 @@ var engine = new Liquid({
|
||||
|
||||
## In-memory Template
|
||||
|
||||
To facilitate rendering w/o files, there's a `templates` option to specify a mapping of filenames and their content. LiquidJS will read templates from the mapping.
|
||||
To facilitate rendering without files, there's a `templates` option to specify a mapping of filenames and their content. LiquidJS will read templates from the mapping.
|
||||
|
||||
```typescript
|
||||
const engine = new Liquid({
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
title: Render Tag Content
|
||||
---
|
||||
|
||||
Custom tags can have content template and can be nested. This article describes how to implement custom tags that consists of a *begin tag*, an *end tag*, and template content between them.
|
||||
Custom tags can have content templates and can be nested. This article describes how to implement custom tags that consist of a *begin tag*, an *end tag*, and template content between them.
|
||||
|
||||
## Render Tag Content
|
||||
|
||||
@@ -22,12 +22,12 @@ Expected output:
|
||||
</div>
|
||||
```
|
||||
|
||||
Firstly, [register][register-tags] a tag with name `wrap` and parse the content into `this.tpls`. Here in `parse(tagToken, remainTokens)`,
|
||||
Firstly, [register][register-tags] a tag named `wrap` and parse the content into `this.tpls`. Here in `parse(tagToken, remainTokens)`:
|
||||
|
||||
- `tagToken` is current token `{%raw%}{% wrap %}{%endraw%}`, and
|
||||
- `remainTokens` is an array of all tokens following `{%raw%}{% wrap %}{%endraw%}` until the end of this template file.
|
||||
|
||||
Basically, what we need to do is take/`.shift()` enough tags from `remainTokens` until we got a `endwrap` token (the name can be arbitrary, but in convention, we need it to be `endwrap`). And if there's no `endwrap` until the end of template file, we need to throw an tag-not-closed `Error`.
|
||||
Basically, what we need to do is take/`.shift()` enough tags from `remainTokens` until we get an `endwrap` token (the name can be arbitrary, but by convention it should be `endwrap`). And if there's no `endwrap` until the end of the template file, we need to throw a tag-not-closed `Error`.
|
||||
|
||||
```javascript
|
||||
engine.registerTag('wrap', {
|
||||
@@ -57,11 +57,11 @@ engine.registerTag('wrap', {
|
||||
})
|
||||
```
|
||||
|
||||
`.renderTemplates()` can be async, we need `yield` to wait it complete. More details on async in LiquidJS, please refer to [Sync and Async][async]. Other parts of `render()` method is quite straightforward. Here's a JSFiddle version: <https://jsfiddle.net/por0zcn1/3/>
|
||||
`.renderTemplates()` can be async; we need `yield` to wait for it to complete. For more details on async in LiquidJS, see [Sync and Async][async]. Other parts of the `render()` method are quite straightforward. Here's a JSFiddle version: <https://jsfiddle.net/por0zcn1/3/>
|
||||
|
||||
## Using ParseStream
|
||||
|
||||
When it comes to complex tags like [for][for] and [if][if], the `parse()` can be very complicated. There's a [ParseStream][ParseStream] utility to organize the `parse()` in event-based style. Following is a re-written `parse()` using `ParseStream` and does exactly the same as above example.
|
||||
When it comes to complex tags like [for][for] and [if][if], the `parse()` can be very complicated. There's a [ParseStream][ParseStream] utility to organize the `parse()` in event-based style. Following is a re-written `parse()` using `ParseStream` that does exactly the same as the example above.
|
||||
|
||||
```javascript
|
||||
parse(tagToken, remainTokens) {
|
||||
@@ -79,7 +79,7 @@ Here's a JSFiddle version: <https://jsfiddle.net/por0zcn1/4/>. For simplicity, t
|
||||
|
||||
## Manipulate the Context
|
||||
|
||||
The `wrap` tag above doesn't seem to be very useful, without using that tag we can render the content anyway. Now we're going to implement a `repeat` tag to render the content 2 times (we can also add a [parameter][parameter] to render arbitrary times).
|
||||
The `wrap` tag above doesn't seem very useful; even without using that tag, we can render the content anyway. Now we're going to implement a `repeat` tag to render the content 2 times (we can also add a [parameter][parameter] to render an arbitrary number of times).
|
||||
|
||||
```liquid
|
||||
{% repeat %}
|
||||
|
||||
@@ -28,7 +28,7 @@ A typical PC handles `1e8` (100M) characters without issues.
|
||||
|
||||
### renderLimit
|
||||
|
||||
Restricting template size alone is insufficient because dynamic loops with large counts can occur in render time. [renderLimit][renderLimit] mitigates this by limiting the time consumed by each `render()` call.
|
||||
Restricting template size alone is insufficient because dynamic loops with large counts can occur during rendering. [renderLimit][renderLimit] mitigates this by limiting the time consumed by each `render()` call.
|
||||
|
||||
```liquid
|
||||
{%- for i in (1..10000000) -%}
|
||||
@@ -49,7 +49,7 @@ Render time is checked on a per-template basis (before rendering each template).
|
||||
|
||||
In other words, `memoryLimit` limits what LiquidJS counts, not every byte your process may allocate.
|
||||
|
||||
Even with small number of templates and iterations, memory usage can grow exponentially. In the following example, memory doubles with each iteration:
|
||||
Even with a small number of templates and iterations, memory usage can grow exponentially. In the following example, memory doubles with each iteration:
|
||||
|
||||
```liquid
|
||||
{% assign array = "1,2,3" | split: "," %}
|
||||
|
||||
@@ -47,7 +47,7 @@ Pre-built UMD bundles are also available:
|
||||
<script src="https://cdn.jsdelivr.net/npm/liquidjs/dist/liquid.browser.umd.js"></script>
|
||||
```
|
||||
|
||||
{% note info Working Demo %} Here's a living demo on jsFiddle: <a href="https://jsfiddle.net/pd4jhzLs/1/" target="_blank">jsfiddle.net/pd4jhzLs/1/</a>, and the source code is also available in <a href="https://github.com/harttle/liquidjs/blob/master/demo/browser/" target="_blank">liquidjs/demo/browser/</a>.{% endnote %}
|
||||
{% note info Working Demo %} Here's a live demo on jsFiddle: <a href="https://jsfiddle.net/pd4jhzLs/1/" target="_blank">jsfiddle.net/pd4jhzLs/1/</a>, and the source code is also available in <a href="https://github.com/harttle/liquidjs/blob/master/demo/browser/" target="_blank">liquidjs/demo/browser/</a>.{% endnote %}
|
||||
|
||||
{% note warn Compatibility %} You may need a <a href="https://github.com/taylorhakes/promise-polyfill" target="_blank">Promise polyfill</a> for legacy browsers like IE and Android UC, see <a href="https://caniuse.com/#feat=promises" target="_blank">caniuse statistics</a>. {% endnote %}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ title: Static Template Analysis
|
||||
{% since %}v10.20.0{% endsince %}
|
||||
|
||||
{% note warn Experimental %}
|
||||
Note that this is an experimental feature and future APIs are subject to change. And internal structures returned can be changed w/o a major version bump.
|
||||
Note that this is an experimental feature and future APIs are subject to change. Internal structures returned can be changed without a major version bump.
|
||||
{% endnote %}
|
||||
|
||||
{% note info Sync and Async %}
|
||||
@@ -234,9 +234,9 @@ This is an example of an object returned from `Liquid.analyze()`, passing it the
|
||||
|
||||
### Analyzing Custom Tags
|
||||
|
||||
For static analysis to include results from custom tags, those tags must implement some additional methods defined on the [Template interface]( /api/interfaces/Template.html). LiquidJS will use the information returned from these methods to traverse the template and report variable usage.
|
||||
For static analysis to include results from custom tags, those tags must implement some additional methods defined on the [Template interface](/api/interfaces/Template.html). LiquidJS will use the information returned from these methods to traverse the template and report variable usage.
|
||||
|
||||
Not all methods are required, depending in the kind of tag. If it's a block with a start tag, end tag and any amount of Liquid markup in between, it will need to implement the [`children()`](/api/interfaces/Template.html#children) method. `children()` is defined as a generator, so that we can use it in synchronous and asynchronous contexts, just like `render()`. It should return HTML content, output statements and tags that are child nodes of the current tag.
|
||||
Not all methods are required, depending on the kind of tag. If it's a block with a start tag, end tag and any amount of Liquid markup in between, it will need to implement the [`children()`](/api/interfaces/Template.html#children) method. `children()` is defined as a generator, so that we can use it in synchronous and asynchronous contexts, just like `render()`. It should return HTML content, output statements and tags that are child nodes of the current tag.
|
||||
|
||||
The [`blockScope()`](/api/interfaces/Template.html#blockScope) method is responsible for telling LiquidJS which names will be in scope for the duration of the tag's block. Some of these names could depend on the tag's arguments, and some will be fixed, like `forloop` from the `{% for %}` tag.
|
||||
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
title: Sync and Async
|
||||
---
|
||||
|
||||
LiquidJS supports both sync and async evaluate, and can be used with Promises. To reuse the same set of tag/filter implementations in both sync and async, LiquidJS tags are implemented as generators.
|
||||
LiquidJS supports both synchronous and asynchronous evaluation, and can be used with Promises. To reuse the same set of tag/filter implementations in both sync and async modes, LiquidJS tags are implemented as generators.
|
||||
|
||||
## Sync and Async API
|
||||
|
||||
All major methods on [Liquid][Liquid] supports both sync and async. These methods return Promises:
|
||||
All major methods on [Liquid][Liquid] support both sync and async. These methods return Promises:
|
||||
|
||||
- `render()`
|
||||
- `renderFile()`
|
||||
@@ -44,11 +44,11 @@ engine.registerTag('upper', class UpperTag extends Tag {
|
||||
})
|
||||
```
|
||||
|
||||
All builtin tags are implemented this way and safe to use in both sync and async (I'll call it *sync-compatible*). To make your custom tag *sync-compatible*, you'll need to:
|
||||
All built-in tags are implemented this way and are safe to use in both sync and async modes (I'll call it *sync-compatible*). To make your custom tag *sync-compatible*, you'll need to:
|
||||
|
||||
- declare render function as `* render()`, in which
|
||||
- do not directly `return <Promise>`, and
|
||||
- do not call any APIs that returns a Promise.
|
||||
- do not call any APIs that return a Promise.
|
||||
|
||||
## Call APIs that return a Promise
|
||||
|
||||
@@ -92,7 +92,7 @@ engine.registerTag('upper', class UpperTag extends Tag {
|
||||
|
||||
## Async only Tags
|
||||
|
||||
If your tag is intend to be used only asynchronously, it can be declared as `async render()` so you can use `await` in its implementation directly:
|
||||
If your tag is intended to be used only asynchronously, it can be declared as `async render()` so you can use `await` in its implementation directly:
|
||||
|
||||
```typescript
|
||||
import { toPromise, TagToken, Context, Emitter, TopLevelToken, Value, Tag, Liquid } from 'liquidjs'
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
title: Truthy and Falsy
|
||||
---
|
||||
|
||||
Though [Liquid][sl] is platform-independent, there're [certain differences][diff] with [the Ruby version][ruby], one of which is the `truthy` value.
|
||||
Though [Liquid][sl] is platform-independent, there are [certain differences][diff] with [the Ruby version][ruby], one of which is the `truthy` value.
|
||||
|
||||
## The Truth Table
|
||||
|
||||
@@ -24,7 +24,7 @@ value | truthy | falsy
|
||||
|
||||
## Use JavaScript Truthy
|
||||
|
||||
Note that liquidjs use Shopify's truthiness by default. But it can be toggled to used standard JavaScript truthiness by setting the **jsTruthy** option to `true`.
|
||||
Note that LiquidJS uses Shopify's truthiness by default. It can be toggled to use standard JavaScript truthiness by setting the **jsTruthy** option to `true`.
|
||||
|
||||
value | truthy | falsy
|
||||
--- | --- | ---
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
title: Use in Express.js
|
||||
---
|
||||
|
||||
LiquidJS is compatible to the [express template engines](https://expressjs.com/en/resources/template-engines.html). You can set liquidjs instance to the [view engine][express-views] option:
|
||||
LiquidJS is compatible with [Express template engines](https://expressjs.com/en/resources/template-engines.html). You can set the LiquidJS instance as the [view engine][express-views] option:
|
||||
|
||||
```javascript
|
||||
var { Liquid } = require('liquidjs');
|
||||
@@ -50,7 +50,7 @@ res.render('world')
|
||||
|
||||
## Caching
|
||||
|
||||
Simply setting the [cache option][cache] to true will enable template caching, as explained in [Caching][Caching]. It's recommended to enable cache in production environment, which can be done by:
|
||||
Simply setting the [cache option][cache] to true will enable template caching, as explained in [Caching][Caching]. It's recommended to enable cache in a production environment, which can be done by:
|
||||
|
||||
```javascript
|
||||
var { Liquid } = require('liquidjs');
|
||||
|
||||
@@ -13,14 +13,14 @@ By default, all tags and output markups lines will generate a NL (`\n`), and whi
|
||||
{{ author }}
|
||||
```
|
||||
|
||||
Outputs (note the blank link):
|
||||
Outputs (note the blank line):
|
||||
|
||||
```
|
||||
|
||||
harttle
|
||||
```
|
||||
|
||||
We can include hyphens in your tag syntax (`{% raw %}{{-{% endraw %}`, `-}}`, `{% raw %}{%-{% endraw %}`, `-%}`) to strip whitespace from left or right. For example:
|
||||
You can include hyphens in tag syntax (`{% raw %}{{-{% endraw %}`, `-}}`, `{% raw %}{%-{% endraw %}`, `-%}`) to strip whitespace from the left or right. For example:
|
||||
|
||||
```liquid
|
||||
{% assign author = "harttle" -%}
|
||||
|
||||
Reference in New Issue
Block a user