Compare commits

...
124 Commits
Author SHA1 Message Date
39233ba9f2 docs: publish .nojekyll so GitHub Pages serves underscore API pages (#952)
EOF

Co-authored-by: Cursor <[email protected]>
2026-09-06 19:38:56 +08:00
allcontributors[bot]GitHuballcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
8f57d9fed8 docs: add sarathfrancis90 as a contributor for code (#951)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2026-09-06 19:16:55 +08:00
Sarath FrancisandGitHub 9af92f5d8c fix(url_decode): keep %2B as a literal plus when decoding (#939)
url_decode decoded the percent-encoding first and only then replaced
"+" with a space, so a "%2B" became "+" and was immediately turned into
a space. Any literal "+" was therefore lost when round-tripped through
url_encode. I now replace "+" with a space before decodeURIComponent,
which lines up with Ruby's CGI.unescape used by Shopify.
2026-09-06 19:16:16 +08:00
semantic-release-bot 747bdbdbee chore(release): 10.29.0 [skip ci]
# [10.29.0](https://github.com/harttle/liquidjs/compare/v10.28.0...v10.29.0) (2026-08-11)

### Features

* add unregisterFilter method ([#946](https://github.com/harttle/liquidjs/issues/946)) ([69b2c58](https://github.com/harttle/liquidjs/commit/69b2c589f9b69a34427cb8533ddb938bd997914f))
* **filters:** add squish filter ([#943](https://github.com/harttle/liquidjs/issues/943)) ([875513f](https://github.com/harttle/liquidjs/commit/875513f4c5136bed0c64562cccabb21a7db8d36c))
2026-08-11 12:53:56 +00:00
MildlyMeticulousandGitHub 875513f4c5 feat(filters): add squish filter (#943) 2026-08-11 20:52:07 +08:00
allcontributors[bot]GitHuballcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
f88a528e27 docs: add YacovGold as a contributor for code (#947)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2026-08-11 20:04:09 +08:00
69b2c589f9 feat: add unregisterFilter method (#946)
* feat: add unregisterFilter method

* docs: show how to re-register built-in filters

---------

Co-authored-by: Yacov <yacov@noemail>
2026-08-11 19:58:25 +08:00
semantic-release-bot 88ae297c1b chore(release): 10.28.0 [skip ci]
# [10.28.0](https://github.com/harttle/liquidjs/compare/v10.27.2...v10.28.0) (2026-08-01)

### Bug Fixes

* **date:** %s returns Unix epoch unaffected by display timezone ([#932](https://github.com/harttle/liquidjs/issues/932)) ([39c8743](https://github.com/harttle/liquidjs/commit/39c87437c5ef38ede9a208c9d55cd13231c6c023)), closes [#931](https://github.com/harttle/liquidjs/issues/931)

### Features

* Add support of inner expressions enclosed by parentheses ([#863](https://github.com/harttle/liquidjs/issues/863)) ([afa5f54](https://github.com/harttle/liquidjs/commit/afa5f5400428fc1ec935aca0282e579224660c95))
2026-08-01 10:18:25 +00:00
afa5f54004 feat: Add support of inner expressions enclosed by parentheses (#863)
* Add support of inner expressions enclosed by parentheses

* Add support of inner expressions enclosed by parentheses

Made-with: Cursor

* simplify implementation

* fix lint

* fix test

* Enhance tests for parenthesized filter chains in Liquid tags. Added scenarios for enabled and disabled grouped expressions in case, for, if, unless tags, ensuring proper handling of expressions and error throwing for invalid syntax.

* test: remove duplicate readGroupedExpression test block

The readGroupedExpression() test suite was duplicated twice in the spec file. Removed the duplicate block to avoid redundant test execution.

* refactor: extract extractGroupedExpressionTokenVariables helper

Extract inline grouped expression variable extraction logic into a dedicated
function for consistency with other extractors (extractFilteredValueVariables,
extractPropertyAccessVariable).

This addresses PR #863 comment 7 - improves code organization and
maintainability.

* refactor(types): explicit type for collection in for tag

collection: ValueToken | GroupedExpressionToken

Addresses PR #863 comment 5.

* refactor: evaluate grouped expressions at render time with resolvedFilters

Addresses PR review comments 4, 6, 8, 9 - moves grouped expression evaluation
from parse-time resolution to render-time lazy evaluation following the
generator-based async/sync duality pattern used throughout liquidjs.

Key changes:
- Replace resolvedValue (Value instance) with resolvedFilters (Filter[])
- Rename resolveGroupedExpressions() to resolveGroupedExpressionFilters()
- Move evaluation logic to evalGroupedExpressionToken() at render time
- Build Filter instances at parse time (carry liquid reference for render)
- Evaluate expression and apply filters lazily via generators
- Add support for tablerow tag with grouped expressions
- Remove duplicate getFilter() method in Value class

Maintains proper layering (tokens → render → templates) and consistency
with Value.value() pattern. Filter resolution still happens at parse time
since it requires liquid.filters access, but actual evaluation is deferred
to render time.

Tags that store raw ValueToken (for, case when-values, tablerow) still need
explicit resolveGroupedExpressionFilters() calls. Tags that wrap with
new Value() get automatic recursive resolution via Value constructor.

* refactor: reuse FilteredValueToken and fix architectural layering

Replace GroupedExpressionToken with existing FilteredValueToken to avoid
code duplication and fix layering violation where tokens depended on
templates (Filter instances).

Key changes:
- Reuse FilteredValueToken instead of GroupedExpressionToken
- Simplify readGroupOrRange() to return FilteredValueToken | RangeToken
- Add liquid reference to Context for runtime filter resolution
- Build Filter instances at render time in evalFilteredValueToken()
- Remove resolveGroupedExpressionFilters() and parse-time resolution
- Remove explicit resolution calls from tag constructors

This maintains proper architectural layering (tokens → render → templates)
with no backward dependencies, as requested in PR review feedback.

All 1537 tests pass.

* revert redundant'

* refactor: make getFilter private and improve code organization

* test: fix test name in case.spec.ts for when disabled block

* refactor: no need for Deprecated flag

* test: fix test name and logic to properly test if tag with nested expressions

* feat: support real parenthesis grouping in grouped expressions

Allow arbitrary expressions inside parentheses (e.g. ((a | upcase) > 3)
and (1 < 3)) when groupedExpressions is enabled, reusing readFilteredValue
for the general case while keeping range and filter-chain fast paths.

* feat: enhance expression tokenization with new generator methods

Added `readExpressionTokensFromHere` and `readGroupedExpressionTokens` methods to improve the handling of expression tokens. This refactor simplifies the token reading process and maintains compatibility with existing grouped expressions, ensuring proper evaluation and filtering.

* add tests

* address comments

---------

Co-authored-by: Omri Rosner <[email protected]>
2026-08-01 18:15:54 +08:00
amit777andGitHub 39c87437c5 fix(date): %s returns Unix epoch unaffected by display timezone (#932)
The %s handler read LiquidDate.getTime(), which returns the
displayDate deliberately shifted by the display timezone offset for
wall-clock getters. With a timezone argument or timezoneOffset
option set, %s produced an epoch shifted by (server offset - display
offset) instead of the true Unix timestamp.

Expose the unshifted time as LiquidDate.dateValue() and use it for
%s. Also switch Math.round to Math.floor so fractional seconds
truncate toward the epoch like Ruby strftime.

Fixes #931
2026-07-10 23:13:07 +08:00
semantic-release-bot 050f161794 chore(release): 10.27.2 [skip ci]
## [10.27.2](https://github.com/harttle/liquidjs/compare/v10.27.1...v10.27.2) (2026-07-09)

### Bug Fixes

* charge join/json/inspect filters by produced output size ([#925](https://github.com/harttle/liquidjs/issues/925)) ([7ab49f9](https://github.com/harttle/liquidjs/commit/7ab49f999ac045ec1e87f3a7a9fd68dd9e8602b3))
* **date:** zero-pad milliseconds when formatting %N fractional seconds ([#929](https://github.com/harttle/liquidjs/issues/929)) ([2634f9d](https://github.com/harttle/liquidjs/commit/2634f9de7b1228cd887b7cab880af8a795c77053))
* enforce ownPropertyOnly for inherited array indices ([#924](https://github.com/harttle/liquidjs/issues/924)) ([552819a](https://github.com/harttle/liquidjs/commit/552819a84b80c62306fe61072628a756272dc749))
* **filters:** modulo should follow divisor sign for negative operands ([#922](https://github.com/harttle/liquidjs/issues/922)) ([568bd5f](https://github.com/harttle/liquidjs/commit/568bd5f9cb99f596292c09fd70b00284b8216f0c))
* **filters:** return empty for out-of-range slice begin or negative length ([#928](https://github.com/harttle/liquidjs/issues/928)) ([f9a1316](https://github.com/harttle/liquidjs/commit/f9a1316d161f4f20018c833160f42dfcf0cde507))
2026-07-09 15:18:38 +00:00
spokodevandGitHub 2634f9de7b fix(date): zero-pad milliseconds when formatting %N fractional seconds (#929)
%N renders the fractional part of the second. The milliseconds returned by
getMilliseconds() are the three most significant digits of that fraction and
must be zero-padded to three digits before use, otherwise sub-100ms values
lose their leading zeros:

  50ms => strftime("%N")  returned "500000000", expected "050000000"
   5ms => strftime("%3N") returned "500",       expected "005"

Pad the milliseconds to three digits before slicing to the requested width.
2026-07-09 23:16:44 +08:00
spokodevandGitHub f9a1316d16 fix(filters): return empty for out-of-range slice begin or negative length (#928)
Ruby/Shopify `slice` returns nil (rendered as an empty string or array) when
the begin offset falls outside the negative range or when the length is
negative. liquidjs forwarded the adjusted indices straight to
Array/String.prototype.slice, whose own negative-index handling produced
non-empty, incorrect output:

  {{ "hello" | slice: -10, 2 }}  => "he"   (expected "")
  {{ "Liquid" | slice: 1, -2 }}  => "iqui" (expected "")

Guard the adjusted begin and the length before slicing.
2026-07-09 22:41:46 +08:00
7ab49f999a fix: charge join/json/inspect filters by produced output size (#925)
* fix(filters): charge join/array_to_sentence_string by output size

join charged memoryLimit by array element count, not by the string it
produces, letting concat doubling (cheap reference copies) inflate an
array's element count and then materialize a huge string via join far
past the configured memoryLimit (GHSA-4r6h-5v86-94p3). Charge by the
sum of stringified element lengths plus separators before allocating.
Apply the same fix to the sibling array_to_sentence_string filter.

Co-authored-by: Cursor <[email protected]>

* refactor(filters): simplify join output-size accounting

Sum stringified element lengths in a single pass and keep the guarded
Array.prototype.join for the result, instead of building an intermediate
parts array.

Co-authored-by: Cursor <[email protected]>

* fix(filters): charge json/jsonify/inspect serialization to memoryLimit

json/jsonify/inspect serialized values without charging memoryLimit, so
a concat-doubled array (cheap reference copies) could be materialized
into a huge JSON string past the configured limit — the same unbounded
class as the join bug (GHSA-4r6h-5v86-94p3). Charge via a JSON.stringify
replacer that accounts string lengths as it walks, aborting mid-
serialization instead of allocating the full blob first.

Co-authored-by: Cursor <[email protected]>

* fix(memory): charge rendered output to memoryLimit at emission

Move output-length accounting into the emitters, which charge each
written chunk against ctx.memoryLimit right before it reaches the
result string or stream. Filters/tags now only pre-charge the extra
working memory they allocate apart from that output, so join drops its
bespoke output-size counting and charges array.length like its siblings.

The block.super capture emitter intentionally omits the limiter to
avoid double-counting content that is re-emitted through the final
emitter.

Co-authored-by: Cursor <[email protected]>

* refactor(filters): rely on emitter output charge for json/inspect/array_to_sentence_string

With rendered output charged at emission, these filters no longer need
bespoke output-size counting: the emitted case is covered by the final
emitter. Revert json/inspect to their original form and array_to_sentence_string
to its element-count charge, dropping the non-emitted `| size` guards.

Co-authored-by: Cursor <[email protected]>

* revert(memory): drop emitter output charge, restore filter output-size accounting

join/array_to_sentence_string/json/inspect charge memoryLimit by the
string they materialize (not element count), so discarded results like
{% assign out = a | join %}{{ out | size }} are still bounded.

Remove the emitter-level limiter added in 2f343f063; it cannot catch
materialized-but-not-emitted values.

Co-authored-by: Cursor <[email protected]>

* fix(filters): charge json/inspect replacer by serialized node size

Replace the flat 1-unit charge for non-string JSON nodes with per-type
estimates (primitives via JSON.stringify length, containers by structure).

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
2026-07-06 23:54:00 +08:00
552819a84b fix: enforce ownPropertyOnly for inherited array indices (#924)
* fix: enforce ownPropertyOnly for inherited array indices

Route array index access (including negative indices, first/last, and the
first/last filters) through a shared readArrayElement helper so that
ownPropertyOnly hides prototype-inherited array indices, closing the
GHSA-fwxr-j5w2-587m bypass. The option's scope (property/index access
only, not filter transforms or iteration) is documented on the option.

Co-authored-by: Cursor <[email protected]>

* fix(filters): invoke Array.prototype methods on unsanitized array values

Call built-ins via Array.prototype.<m>.call(...) for values that come
from scope (join, compact, concat, slice, where/reject) so an overridden
instance method on unsanitized data cannot hijack filter behavior.
Methods on freshly-created arrays are left as-is.

Co-authored-by: Cursor <[email protected]>

* fix(filters): use String.prototype.slice for the string branch of slice

Route the non-array branch through String.prototype.slice.call so the
slice filter never dispatches through a possibly-overridden instance
method, matching the Array.prototype guard.

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
2026-07-06 20:12:09 +08:00
allcontributors[bot]GitHuballcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
8bfb6428ae docs: add spokodev as a contributor for code (#923)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2026-06-26 01:21:05 +08:00
spokodevandGitHub 568bd5f9cb fix(filters): modulo should follow divisor sign for negative operands (#922)
The `modulo` filter used JavaScript's `%` (truncated remainder, sign
follows the dividend). Shopify/Ruby Liquid uses floored modulo, where the
result takes the sign of the divisor. Since liquidjs advertises Shopify
compatibility, negative operands produced the wrong sign.

Use `((v % arg) + arg) % arg` to match Ruby's `%`. Positive-operand
results are unchanged.
2026-06-26 01:19:59 +08:00
semantic-release-bot ed489865b6 chore(release): 10.27.1 [skip ci]
## [10.27.1](https://github.com/harttle/liquidjs/compare/v10.27.0...v10.27.1) (2026-06-23)

### Bug Fixes

* improve round function; improvement to [#873](https://github.com/harttle/liquidjs/issues/873) ([#901](https://github.com/harttle/liquidjs/issues/901)) ([956b51e](https://github.com/harttle/liquidjs/commit/956b51ea953eb52d9eba7409b7f51e379023fec4))
* **security:** charge pop filter allocation to memoryLimit ([#907](https://github.com/harttle/liquidjs/issues/907)) ([8a0c74a](https://github.com/harttle/liquidjs/commit/8a0c74a7fcb1671aa1dcb71ec82ba0602dc90d04))
* **strip_html:** infinite loop for strip_html ([5c3522f](https://github.com/harttle/liquidjs/commit/5c3522f33928aae66f0fe85c36e1d9015c768fe2))

### Performance Improvements

* **parser:** memoize createTrie to avoid rebuilding tries per Tokenizer ([#911](https://github.com/harttle/liquidjs/issues/911)) ([3a0d80d](https://github.com/harttle/liquidjs/commit/3a0d80d1f4526af0fbca2bb2e0a9c51669d2fd3e))
2026-06-23 10:43:45 +00:00
afec88b04c docs(readme): README overhaul, used-by grid, and docs homepage (#914)
* docs(readme): lead with quick start and scannable structure

Restructure the README to match common OSS conventions: tagline and
badges above the fold, copy-paste Quick start, Features list, and a
compact Used by section. Remove the star plea, centered logo, and
per-project marketing blurbs that pushed useful content down.

Co-authored-by: Cursor <[email protected]>

* docs(readme): playground GIF, used-by grid, and docs homepage sync

Add data/used-by.json with build:used-by for README and docs homepage, playground demo capture, and shared home-section layout. Used by lists products with site logos; Financial Support keeps org and individual sponsors.

Co-authored-by: Cursor <[email protected]>

* chore: use .local for playground capture scratch files

Co-authored-by: Cursor <[email protected]>

* fix: satisfy eslint in build-used-by and capture scripts

Co-authored-by: Cursor <[email protected]>

* chore: drop one-off playground capture script

Co-authored-by: Cursor <[email protected]>

* refactor(docs): copy Used by from README like financial contributors

Drop data/used-by.json and build-used-by.js; build-contributors.js now extracts USED-BY-BEGIN/END to used-by.swig.

Co-authored-by: Cursor <[email protected]>

* refactor(docs): inline Used by section, drop home-section partial

Co-authored-by: Cursor <[email protected]>

* fix(docs): drop redundant logo styles from .contributors

Co-authored-by: Cursor <[email protected]>

* fix(docs): build liquid bundle before hexo serve

Co-authored-by: Cursor <[email protected]>

* refactor(docs): drop playground window chrome from capture demo

Co-authored-by: Cursor <[email protected]>

* refactor(docs): revert playground capture changes to master behavior

Restore Ace output pane, drop Prism and output-preview styling. Simplify docs:dev to rely on docs prestart.

Co-authored-by: Cursor <[email protected]>

* refactor(docs): rely on docs prebuild for liquid bundle and contributors

Co-authored-by: Cursor <[email protected]>

* feat(docs): show playground output as Prism-highlighted HTML code

Co-authored-by: Cursor <[email protected]>

* feat(docs): polish playground layout and regenerate README demo GIF

* fix(docs): align playground GIF capture with live editor styling

* fix(docs): unify playground pane padding and hold output on errors

Match editor inset to the output panel, drop Prism from output preview,
keep the last render while typing invalid template/context, and refresh
the README demo GIF.

* fix(docs): regenerate playground GIF with held output during typing

* feat(docs): sync Used by logos and polish playground

Inline README Used by grid on the docs homepage, refine playground layout and live output behavior, and drop the unused build-used-by script from package scripts.

Co-authored-by: Cursor <[email protected]>

* fix(docs): restore Rock RMS logo and remove duplicate entry

Restore the official Rock RMS wordmark (GetImage.ashx?id=72534) instead of the SparkDevNetwork GitHub org avatar that was wrongly substituted for it.

Co-authored-by: Cursor <[email protected]>

* fix(docs): regenerate playground GIF with live indicator states

Restore the capture script for the new pane-indicator layout so the README demo shows correct idle/active/pending/ok colors and pulsing animations while typing.

* fix(docs): static playground GIF with correct indicator colors

Capture one frame per keystroke with animations disabled so dot states
(idle/active/pending/ok) match the live playground without pulsing.

Co-authored-by: Cursor <[email protected]>

* docs: use square Rock RMS icon in Used by section

Co-authored-by: Cursor <[email protected]>

* fix(docs): ensure capture indicator colors apply instantly

Disable indicator transitions and cancel active animations before
setting data-state so pending yellow is not stuck on the prior ok green.

Co-authored-by: Cursor <[email protected]>

* docs: point Microsoft Used by link to microsoft.com

The merged tile title covers Power Pages and Azure API Management; href should go to Microsoft home, not Power Pages only.

Co-authored-by: Cursor <[email protected]>

* docs: remove Dailycontributors from Used by section

No evidence they run on LiquidJS; they are an OpenCollective sponsor only.

Co-authored-by: Cursor <[email protected]>

* docs: reword intro to say Liquid, not Shopify Liquid

Move Shopify into the compatibility list and drop the shopify/liquid link from README; align package.json description.

Co-authored-by: Cursor <[email protected]>

* fix(docs): restore playground output as Prism-highlighted HTML

Co-authored-by: Cursor <[email protected]>

* docs: add extensible to README intro and package description

EOF

Co-authored-by: Cursor <[email protected]>

* chore: move playground capture script to .local

Co-authored-by: Cursor <[email protected]>

* fix(docs): drop unused Ace mode-html from playground

Output pane uses Prism, not Ace; template and context editors still need liquid/json modes and basePath for themes.

Co-authored-by: Cursor <[email protected]>

* docs: sync intro sentence across package and site metadata

Align package.json, docs config, manifest, llms.txt, and AGENTS.md tagline to the README canonical description.

Co-authored-by: Cursor <[email protected]>

* docs: trim verbose intro in intro-to-liquid tutorial

Remove README tagline and repo-purpose copy duplicated by the recent metadata sync.

Co-authored-by: Cursor <[email protected]>

* docs: shorten homepage banner subtitle

Trim docs site banner and short taglines after the em dash; keep full description for meta tags and npm/README.

* docs: simplify playground GIF caption in README

Co-authored-by: Cursor <[email protected]>

* docs: dedupe homepage subtitle and description into _config.yml

Remove redundant front matter from index.pug; theme falls back to site config for banner and meta tags.

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
2026-06-23 17:39:19 +08:00
Max MedveandGitHub 3a0d80d1f4 perf(parser): memoize createTrie to avoid rebuilding tries per Tokenizer (#911)
The Tokenizer constructor calls createTrie(operators) and
createTrie(literalValues) on every instantiation, and liquidjs builds a
fresh Tokenizer per output/tag while parsing. On typical templates this
rebuilt the same prefix-tries dozens of times and showed up as a large
share of parse CPU in profiling.

Memoize createTrie with a module-level WeakMap keyed on the input object.
The inputs (operators, literalValues) are stable references and the trie
is only ever read afterward (via matchTrie), never mutated, so caching by
reference is behavior-preserving. WeakMap (not Map) lets short-lived,
per-instance operator objects and their tries be garbage collected.
2026-06-22 20:11:06 +08:00
Timmy BraunandGitHub 956b51ea95 fix: improve round function; improvement to #873 (#901) 2026-06-22 20:07:27 +08:00
Yang JunandGitHub 5c3522f339 fix(strip_html): infinite loop for strip_html 2026-06-22 02:28:07 +08:00
6d00257e15 docs: add AGENTS.md and llms.txt for AI agents (#919)
Co-authored-by: Cursor <[email protected]>
2026-06-22 02:24:54 +08:00
03a30e6dc4 docs: replace CookieHub with cookieconsent (#918)
Co-authored-by: Cursor <[email protected]>
2026-06-22 01:34:53 +08:00
4775227358 docs(security): route vulnerability reports to GitHub Advisories (#913)
Replace the private email contact with GitHub Security Advisories and
set the common-case fix expectation to within a month.

Co-authored-by: Cursor <[email protected]>
2026-06-20 00:00:05 +08:00
8a0c74a7fc fix(security): charge pop filter allocation to memoryLimit (#907)
* fix(security): charge pop filter allocation to memoryLimit (CWE-770)

The `pop` array filter cloned the input via `[...toArray(v)]` without
charging `this.context.memoryLimit.use(...)`, bypassing the memoryLimit
DoS guard that its sibling filters (shift, unshift, compact, etc.) apply.
Mirror `shift` to account for the O(N) allocation.

Co-authored-by: Cursor <[email protected]>

* fix(security): charge sample filter full clone allocation to memoryLimit (CWE-770)

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
2026-06-14 15:50:50 +08:00
ed15a52c26 docs: revisit wording & style for liquidjs.com (#906)
* docs: polish theme, playground, and reference pages

Improve readability of the docs site with updated light/dark tokens, shared
code-block styling, and playground editors that follow system color scheme.
Skip CookieHub on localhost, serve the browser bundle from theme source, and
use backtick titles on filter/tag reference pages for consistent navigation.

Co-authored-by: Cursor <[email protected]>

* 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]>

* docs: restore lowercase filter and tag titles

Titles should match actual filter/tag identifiers (e.g. abs, append), not capitalized English labels.

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
2026-06-08 00:26:52 +08:00
499b221f33 docs: remove translations & update homepage (#904)
* docs: add GitHub buttons and improve option docs

* chore: replace husky with prepush check

* docs: revamp homepage and switch to custom GitHub buttons

- Make the docs English-only by removing all zh-cn content, the language switcher UI, and related JS/config

- Rework homepage feature cards (Safe & Typed, Pure JavaScript, Shopify & Jekyll, Streaming) and refresh section colors/layout

- Replace buttons.github.io with custom Star/Sponsor buttons featuring a live star count and dark-mode support

- Drop the buttons.js script and tidy banner, header, footer, and share partials

Co-authored-by: Cursor <[email protected]>

* fix: restore tsconfig settings and changelog build

Re-add suppressImplicitAnyIndexErrors and downlevelIteration removed in
a75033e2c, which broke the rollup TypeScript build on CI. Drop zh-cn
changelog output now that translations were removed.

Co-authored-by: Cursor <[email protected]>

* fix: resolve TS errors without deprecated tsconfig options

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
2026-06-07 01:37:51 +08:00
Yang JunandGitHub 705e5d1b6e docs: add consent banner and GA (#903) 2026-06-06 14:04:21 +08:00
semantic-release-bot a8fd734b5e chore(release): 10.27.0 [skip ci]
# [10.27.0](https://github.com/harttle/liquidjs/compare/v10.26.0...v10.27.0) (2026-05-15)

### Features

* **context:** null-prototype scope frames via createScope ([#899](https://github.com/harttle/liquidjs/issues/899)) ([47d3f1b](https://github.com/harttle/liquidjs/commit/47d3f1b1cf33be91fe587821f288d1c9d8e1ace7))
2026-05-15 18:21:41 +00:00
47d3f1b1cf feat(context): null-prototype scope frames via createScope (#899)
- Add createScope() building Object.create(null) with optional own props

- Initialize context stack bottom with createScope() for assign/capture

- Push null-proto scopes from for, tablerow, block, layout, include (incl. Jekyll)

Co-authored-by: Cursor <[email protected]>
2026-05-16 02:20:03 +08:00
semantic-release-bot c20c0af02d chore(release): 10.26.0 [skip ci]
# [10.26.0](https://github.com/harttle/liquidjs/compare/v10.25.7...v10.26.0) (2026-05-14)

### Bug Fixes

* **date:** cap strftime widths and account padding in memoryLimit ([#895](https://github.com/harttle/liquidjs/issues/895)) ([3129d46](https://github.com/harttle/liquidjs/commit/3129d46dc95efa357b00e5a57ee1af80a13d72ed))
* enforce renderLimit for empty renderTemplates calls ([#894](https://github.com/harttle/liquidjs/issues/894)) ([5b9c346](https://github.com/harttle/liquidjs/commit/5b9c3469085e01c79e2d0af28e2a13f730e1793d))
* propagate ownPropertyOnly into Context.spawn() for {% render %} ([#893](https://github.com/harttle/liquidjs/issues/893)) ([dbbf628](https://github.com/harttle/liquidjs/commit/dbbf6288030591bf6da28d8c1cce5a17bca97bb6))
* **security:** block Object.prototype filter/tag lookups (RCE) ([#897](https://github.com/harttle/liquidjs/issues/897)) ([457fae0](https://github.com/harttle/liquidjs/commit/457fae0736c3ec862539b9dbf7f477e6c08fb6c6))
* strip html newline tags ([#892](https://github.com/harttle/liquidjs/issues/892)) ([26ea285](https://github.com/harttle/liquidjs/commit/26ea2856c7a90aec892b98d94a9b7a3e18539045))
* **strip_html:** rewrite as linear single-pass scan to avoid ReDoS ([#896](https://github.com/harttle/liquidjs/issues/896)) ([3616a74](https://github.com/harttle/liquidjs/commit/3616a744b9abeb425c217b340a2397d46176afb8))

### Features

* add sha256 and hmac_sha256 filters for cryptographic operations ([#889](https://github.com/harttle/liquidjs/issues/889)) ([1c816d4](https://github.com/harttle/liquidjs/commit/1c816d4fc3bcd2cba011f7a84f56a4251fca0622))
2026-05-14 14:23:44 +00:00
457fae0736 fix(security): block Object.prototype filter/tag lookups (RCE) (#897)
* fix(security): block Object.prototype filter/tag lookups (RCE)

`liquid.filters` and `liquid.tags` were plain `{}` so bracket access on
template-controlled keys inherited from `Object.prototype`. Most damaging:
`{{ x | valueOf }}` resolved to `Object.prototype.valueOf`, which the
filter pipeline called as a handler with `this = FilterImpl`; valueOf
returns its receiver, leaking `context`, `liquid`, `token` (and via them
parser, loader, fs) into the template — chain that with `group_by`/`where`
gadgets and an attacker reaches `Function`/`child_process` for RCE.
Same shape on the tag side: `{% constructor %}` bypassed the
"tag not found" assertion and crashed with a confusing message.

Use null-prototype storage so `liquid.filters[name]` / `liquid.tags[name]`
only resolve to explicitly registered entries. The existing
`assert(impl || !strictFilters)` and `assert(TagClass, ...)` now do the
right thing for `valueOf`, `toString`, `constructor`, `__proto__`,
`hasOwnProperty`, `isPrototypeOf`, `__defineGetter__`, etc.

Co-authored-by: Cursor <[email protected]>

* test: fold prototype-registry regressions into register + e2e

Co-authored-by: Cursor <[email protected]>

* test: assert null-prototype registries vs all Object.prototype keys

Co-authored-by: Cursor <[email protected]>

* test: dedupe registry checks; merge filter prototype loop

Co-authored-by: Cursor <[email protected]>

* fix(context): use null-prototype scope and register objects

Add createScope(); use for bottom scope, spawn default, getAll merge, ctx.push frames, filter loops, include/layout blocks registers, and cycle groups. registers uses Object.create(null) and getRegister uses ??.

For-loop continue register defaults to 0 (not {}): Array.slice coerces plain {} but not null-prototype objects.

Export createScope from the package entry.

Co-authored-by: Cursor <[email protected]>

* revert(context): plain {} registers and getRegister ||

Registers are only mutated by tag implementations, not templates; keep null-prototype scopes/createScope for push frames.

Co-authored-by: Cursor <[email protected]>

* test(context): assert scope isolation without probing prototypes

Replace Object.getPrototypeOf checks for bottom() and getAll() with
'in' checks on typical Object.prototype names plus a merge assertion.

Co-authored-by: Cursor <[email protected]>

* test(e2e): assert constructor filter/tag lookups (node + UMD)

Co-authored-by: Cursor <[email protected]>

* test(context): cover Object.prototype keys under ownPropertyOnly

- Add getSync cases for constructor and valueOf on plain objects
- Remove scope storage tests that used the in operator

Co-authored-by: Cursor <[email protected]>

* refactor: remove createScope helper

Drop the exported helper and finish migrating call sites. Revert incidental context/for/include/layout churn so behavior matches mainline aside from the removal. Trim duplicate e2e and heavy Object.prototype loops in registry tests.

Co-authored-by: Cursor <[email protected]>

* docs: document ownPropertyOnly and Drop security in security model

Co-authored-by: Cursor <[email protected]>

* docs(zh-cn): sync security model with ownPropertyOnly and Drop notes

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
2026-05-14 22:18:10 +08:00
3616a744b9 fix(strip_html): rewrite as linear single-pass scan to avoid ReDoS (#896)
* fix(strip_html): rewrite as linear single-pass scan to avoid ReDoS

The previous strip_html regex
  /<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>|<[\s\S]*?>|<!--[\s\S]*?-->/g
contains lazy alternatives that backtrack O(n^2) on inputs with many
unclosed `<script` / `<style` openers. A 350KB payload of
`'<script'.repeat(50000)` blocked the Node.js event loop for ~10s, and
cost grew quadratically with input size. memoryLimit only charged
str.length, which does not bound regex CPU.

Replace the regex with an indexOf-based single-pass scan. For each `<`
we:
- if `<script` opener: find next `</script>` and skip the whole block;
  cache "no closer after pos k" so subsequent unclosed `<script`
  openers do not re-scan the tail.
- same for `<style` / `</style>`.
- otherwise treat as a generic `<...>` tag (matches the original
  behavior, where the `<[\s\S]*?>` alternative also caught comments).
- if no closing `>` exists, emit the tail as literal text and stop.

Total work is O(n). All existing strip_html test cases pass unchanged.

Add regression tests covering the PoCs (`<script` / `<style` repeats,
and `<script>foo` repeats with `>` but no `</script>`) plus a
memoryLimit assertion.

Co-authored-by: Cursor <[email protected]>

* refactor(strip_html): factor block kinds into a small table

Same algorithm and complexity, fewer lines. Document why a regex-only
solution can't be O(n) in V8 (no atomic groups / possessive quantifiers
/ memoization, so unrolled-loop patterns are still O(n^2) on unclosed
openers — empirically confirmed: original 280KB ~4s, Friedl unrolled
~14s, atomic lookahead ~7s; tokenizer ~1ms).

Co-authored-by: Cursor <[email protected]>

* refactor(strip_html): inline block kinds to match file style

Drop the module-level STRIP_BLOCKS table; the rest of the file keeps
each filter self-contained (only escapeMap/unescapeMap are top-level
maps shared across filters). Two openers don't justify a table.

Co-authored-by: Cursor <[email protected]>

* refactor(strip_html): unify raw-text blocks; treat <!--...--> as opaque

In HTML5, <script>, <style>, and <!-- --> are all raw-text blocks: their
content is opaque until the matching closer, so a `>` inside CSS, JS, or
a comment must not be treated as a tag end. The previous code only had
this special handling for <script> and <style>; comments containing `>`
fell through to the generic `<...>` branch and were partially stripped
(e.g. `<!-- a > b -->` left `b -->` in the output).

Match Shopify Liquid's STRIP_HTML_BLOCKS set (script + style + comment),
and consolidate the three near-identical branches into a small
opener/closer table inside the function.

Algorithm and complexity unchanged (O(n) via indexOf + cached closer
positions). Add a regression test for `>` inside a comment.

Co-authored-by: Cursor <[email protected]>

* refactor(strip_html): drop position cache, delete dead blocks from Set

Once `indexOf(closer, X)` returns -1, all subsequent searches (with
monotonically increasing start) also return -1. So tracking absence is
enough; storing positions is unnecessary. Make `blocks` a Set and
delete a kind once its closer is known absent — no parallel `dead`
bookkeeping. Use Jest's per-test timeout for the ReDoS regressions
instead of manual Date.now() bookkeeping.

Co-authored-by: Cursor <[email protected]>

* refactor(strip_html): treat '<...>' as a catch-all block kind

Adding ['<', '>'] as the lowest-priority entry of `blocks` lets the
inner loop subsume the generic-tag fallback: the `end` sentinel and
its `< 0` / `<= 0` follow-up checks disappear, the "no terminator"
exit becomes a single `i === lt` test, and Set<[string, string]>
collapses to Map<string, string>.

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
2026-05-11 23:59:40 +08:00
3129d46dc9 fix(date): cap strftime widths and account padding in memoryLimit (#895)
* fix(date): cap strftime widths and account padding in memoryLimit

- Clamp numeric strftime pad widths to MAX_STRFTIME_PAD (1024)
- Export estimateStrftimePaddingMemory for the date filter to charge memoryLimit
- Replace unbounded pad() concatenation loop with ch.repeat + single concat
- Add regression tests for clamping and memoryLimit on huge %width directives

Co-authored-by: Cursor <[email protected]>

* fix(date): harden strftime memory accounting and document security model

Move strftime memory charging into the same formatting path used for padding, enforce pre-allocation checks, and add regression tests for non-string date format PoCs. Add dedicated docs clarifying that memoryLimit is cooperative DoS mitigation and not strict heap isolation.

Co-authored-by: Cursor <[email protected]>

* docs(zh-cn): add security model docs for DoS limits

Add a Chinese security-model tutorial and link it from the Chinese DoS guide to clarify that memoryLimit is cooperative accounting, list uncounted custom conversion cases, and recommend avoiding fully user-defined templates in online services.

Co-authored-by: Cursor <[email protected]>

* docs: consolidate DoS docs into security-model pages

Merge DoS guidance into security-model docs in both English and Chinese, and remove the placeholder dos.md pages to avoid duplicate/redirect-only docs.

Co-authored-by: Cursor <[email protected]>

* docs: merge DoS details into security-model docs

Move the detailed parseLimit/renderLimit/memoryLimit explanations and examples into the English and Chinese security-model pages so content from the removed dos pages is preserved.

Co-authored-by: Cursor <[email protected]>

* docs: reorganize security-model structure for clarity

Restructure English and Chinese security-model docs into a consistent flow: security boundary, limits overview, per-limit details, and online service guidance.

Co-authored-by: Cursor <[email protected]>

* refactor(strftime): simplify %N width parsing logic

Use regex-backed width assumptions to simplify %N width normalization and padding memory accounting while keeping behavior equivalent.

Co-authored-by: Cursor <[email protected]>

* refactor(strftime): rely on memoryLimit for width control

Remove MAX_STRFTIME_PAD hard capping and rely on memoryLimit enforcement before padding allocation. Update strftime/date tests and security-model docs to match the new boundary and renderLimit caveats.

Co-authored-by: Cursor <[email protected]>

* fix(strftime): use add() once for padding, minimize churn

- pad(): replace per-char loop with a single add(str, ch.repeat(n)) call.
  The earlier `probe[0] === ch` heuristic was wrong when ch happened to
  equal a leading char of 'probe' (e.g. ch === 'p').
- strftime.ts: revert unrelated typing/structural refactors so the diff
  contains only the memoryLimit threading and the %N memory charge.
- docs: rewire the deleted dos.html sidebar entry to security-model.html
  (with localized labels) so the deleted page does not 404 from the
  sidebar.

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
2026-05-10 14:35:28 +08:00
5b9c346908 fix: enforce renderLimit for empty renderTemplates calls (#894)
renderLimit was only checked inside the per-template loop, so
renderTemplates([], ...) skipped it. Empty {% for %} and {% tablerow %}
bodies call that path once per iteration (tablerow still does emitter
work for <tr>/<td>), bypassing the documented time budget. Check the
limiter at renderTemplates entry before the loop.

Add regression tests for empty for-body and empty tablerow-body.

Co-authored-by: Cursor <[email protected]>
2026-05-07 23:03:43 +08:00
dbbf628803 fix: propagate ownPropertyOnly into Context.spawn() for {% render %} (#893)
Child contexts from spawn() re-derived ownPropertyOnly from Liquid opts
only, dropping per-render RenderOptions overrides. That broke the contract
that parseAndRender(..., { ownPropertyOnly: true }) locks down a single
render, including partials loaded via {% render %}.

Add regression test matching prototype-chain leak PoC.

Co-authored-by: Cursor <[email protected]>
2026-05-03 22:35:31 +08:00
26ea2856c7 fix: strip html newline tags (#892)
* docs: add @talboren as financial contributor

* fix(strip_html): match tags that span newlines inside angle brackets

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
2026-05-03 21:36:09 +08:00
a55f543f49 docs(readme): add Freshet to Who's Using LiquidJS (#888)
Co-authored-by: MattAltermatt <[email protected]>
2026-05-03 12:05:12 +08:00
allcontributors[bot]GitHuballcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
d1d517d1ec docs: add VladimirFilonov as a contributor for code (#891)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2026-05-03 12:03:52 +08:00
Vladimir FilonovandGitHub 1c816d4fc3 feat: add sha256 and hmac_sha256 filters for cryptographic operations (#889) 2026-05-03 12:03:26 +08:00
semantic-release-bot 34877950bf chore(release): 10.25.7 [skip ci]
## [10.25.7](https://github.com/harttle/liquidjs/compare/v10.25.6...v10.25.7) (2026-04-23)

### Bug Fixes

* **filters:** support Buffer input in base64_encode to prevent binary data corruption ([#881](https://github.com/harttle/liquidjs/issues/881)) ([0ee6dbb](https://github.com/harttle/liquidjs/commit/0ee6dbb511aa926f6d490293282060abf3bab37f))
2026-04-23 13:41:11 +00:00
Yang JunandGitHub 75c815a4d7 docs: add @talboren as financial contributor (#886) 2026-04-23 21:39:50 +08:00
allcontributors[bot]GitHuballcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
f1f896c29d docs: add talboren as a contributor for code (#885)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2026-04-23 21:31:50 +08:00
TalandGitHub 0ee6dbb511 fix(filters): support Buffer input in base64_encode to prevent binary data corruption (#881)
* fix: support Buffer input in base64_encode filter

When binary data (e.g. images, PDFs) is passed through the template
context as a Node.js Buffer, the base64_encode filter would call
stringify() on it first, which internally does String(value). This
triggers Buffer.toString() with the default 'utf-8' encoding, which
is a lossy conversion for non-UTF-8 byte sequences — invalid bytes
get replaced with U+FFFD, permanently destroying the original data.

The fix checks for Buffer.isBuffer() before stringify, and calls
buffer.toString('base64') directly, bypassing the lossy UTF-8
intermediate step. String inputs continue through the existing path
unchanged.

Made-with: Cursor

* fix: handle Buffer in filter layer to fix browser build

Move Buffer handling from base64-impl.ts (which gets swapped for the
browser impl at build time) into base64.ts (the filter layer). This
avoids a type error during the browser rollup build where the browser
impl only accepts string.

Also guard Buffer.isBuffer() with typeof Buffer !== 'undefined' for
safety in browser environments.

Made-with: Cursor
2026-04-23 21:30:58 +08:00
semantic-release-bot 30e04ba16d chore(release): 10.25.6 [skip ci]
## [10.25.6](https://github.com/harttle/liquidjs/compare/v10.25.5...v10.25.6) (2026-04-19)

### Bug Fixes

* nested block for layout ([#883](https://github.com/harttle/liquidjs/issues/883)) ([e2311df](https://github.com/harttle/liquidjs/commit/e2311dfd6e82f73509308aa8a3a1fafc92e226f0))
2026-04-19 15:42:53 +00:00
Yang JunandGitHub e2311dfd6e fix: nested block for layout (#883) 2026-04-19 23:41:35 +08:00
Yang JunandGitHub 2def22c85e docs(readme): add Kibana to README.md (#882)
* docs(readme): add Kibana and Sentry to Who's Using LiquidJS

Made-with: Cursor

* docs(readme): drop Semgrep and Sentry from Who's Using; keep Kibana

Made-with: Cursor

* docs(readme): restore Sentry in financial sponsors block

Made-with: Cursor

* docs(readme): restore Timmy Braun in all-contributors table

Made-with: Cursor
2026-04-19 21:38:15 +08:00
semantic-release-bot 4af7be695c chore(release): 10.25.5 [skip ci]
## [10.25.5](https://github.com/harttle/liquidjs/compare/v10.25.4...v10.25.5) (2026-04-07)

### Bug Fixes

* enforce root containment for renderFile/parseFile lookups ([#870](https://github.com/harttle/liquidjs/issues/870)) ([f41c1fc](https://github.com/harttle/liquidjs/commit/f41c1fc02fe901598f3328118b42b13bc6bc9b04))
* null date should return empty ([#868](https://github.com/harttle/liquidjs/issues/868)) ([#872](https://github.com/harttle/liquidjs/issues/872)) ([4f9a499](https://github.com/harttle/liquidjs/commit/4f9a49988a93c156524981e189a4fec238e682b8))
* rounding negative away from zero when half ([#873](https://github.com/harttle/liquidjs/issues/873)) ([1cdf10b](https://github.com/harttle/liquidjs/commit/1cdf10b57d82f0592414efbfca19e204b37aea9f))
2026-04-07 17:18:16 +00:00
Yang JunandGitHub 05c47da46d refactor: replace shell scripts with JS for cross-platform support (#875)
Convert bin/ shell scripts to Node.js and npm scripts using shx and npm-run-all2. Remove unused build-icons.sh. Inlined simple scripts (build-docs-liquid, build-apidoc) as npm scripts.

Made-with: Cursor
2026-04-08 01:16:49 +08:00
allcontributors[bot]GitHuballcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
66011d14b0 docs: add timbze as a contributor for code (#874)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2026-04-08 00:53:27 +08:00
Timmy BraunandGitHub 1cdf10b57d fix: rounding negative away from zero when half (#873) 2026-04-08 00:52:35 +08:00
Timmy BraunandGitHub 4f9a49988a fix: null date should return empty (#868) (#872) 2026-04-08 00:10:33 +08:00
Yang JunandGitHub f41c1fc02f fix: enforce root containment for renderFile/parseFile lookups (#870)
Made-with: Cursor
2026-04-07 23:18:53 +08:00
semantic-release-bot db4348507e chore(release): 10.25.4 [skip ci]
## [10.25.4](https://github.com/harttle/liquidjs/compare/v10.25.3...v10.25.4) (2026-04-07)

### Bug Fixes

* sort and sort_natural filters bypass ownPropertyOnly ([#869](https://github.com/harttle/liquidjs/issues/869)) ([e743da0](https://github.com/harttle/liquidjs/commit/e743da0020d34e2ee547e1cc1a86b58377ebe1ce))
2026-04-07 13:02:49 +00:00
Yang JunandGitHub e743da0020 fix: sort and sort_natural filters bypass ownPropertyOnly (#869)
Use _getFromScope for property access in sort/sort_natural filters to respect the ownPropertyOnly security option, preventing prototype chain traversal that could leak sensitive inherited properties.

Also extract shared sortBy helper, add orderedCompare with nil handling consistent with caseInsensitiveCompare and Ruby Liquid.

Made-with: Cursor
2026-04-07 21:01:20 +08:00
semantic-release-bot 8f69a08399 chore(release): 10.25.3 [skip ci]
## [10.25.3](https://github.com/harttle/liquidjs/compare/v10.25.2...v10.25.3) (2026-04-06)

### Bug Fixes

* precise memoryLimit for string replace ([abc058b](https://github.com/harttle/liquidjs/commit/abc058be0f33d6372cd2216f4945183167abeb25))
* use realpath for fs.contains ([#867](https://github.com/harttle/liquidjs/issues/867)) ([529dd67](https://github.com/harttle/liquidjs/commit/529dd67eeb6b125637623d6a723601f0938d3613))
2026-04-06 06:45:50 +00:00
Yang JunandGitHub 529dd67eeb fix: use realpath for fs.contains (#867)
* fix: use realpath for fs.contains

* chore: reset file mode changes

Made-with: Cursor

* fix: Windows compat for contains/containsSync and toLiquidAsync arg order

Made-with: Cursor
2026-04-06 14:40:35 +08:00
Harttle abc058be0f fix: precise memoryLimit for string replace 2026-03-26 19:36:31 +08:00
semantic-release-bot 521177e3f6 chore(release): 10.25.2 [skip ci]
## [10.25.2](https://github.com/harttle/liquidjs/compare/v10.25.1...v10.25.2) (2026-03-25)

### Bug Fixes

* handle undefined replacement argument in replace filter ([#864](https://github.com/harttle/liquidjs/issues/864)) ([0ad2b11](https://github.com/harttle/liquidjs/commit/0ad2b11ab15e7da608a9ef936b2a00a6a6517038))
2026-03-25 17:20:39 +00:00
allcontributors[bot]GitHuballcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
75e06eff92 docs: add joecottam as a contributor for code (#865)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2026-03-26 01:19:19 +08:00
Joe CottamandGitHub 0ad2b11ab1 fix: handle undefined replacement argument in replace filter (#864) 2026-03-26 01:18:40 +08:00
semantic-release-bot 97d829116c chore(release): 10.25.1 [skip ci]
## [10.25.1](https://github.com/harttle/liquidjs/compare/v10.25.0...v10.25.1) (2026-03-22)

### Bug Fixes

* mem limiter for invalid ranges ([95ddefc](https://github.com/harttle/liquidjs/commit/95ddefc056a11a44d9e753fd47a39db2c241e578))
* treat args for replace_first as literal ([35d5230](https://github.com/harttle/liquidjs/commit/35d523026345d80458df24c72e653db78b5d061d))
2026-03-22 14:18:52 +00:00
Harttle 35d5230263 fix: treat args for replace_first as literal 2026-03-22 22:16:45 +08:00
Harttle 94440a0653 chore: more strict mem limit for string filters 2026-03-22 22:10:39 +08:00
Yang JunandHarttle 95ddefc056 fix: mem limiter for invalid ranges 2026-03-22 10:24:03 +08:00
Yang JunandGitHub 1b85fdaa9c docs: update contact in security.md (#862) 2026-03-08 15:41:45 +08:00
semantic-release-bot 93c38c7c6d chore(release): 10.25.0 [skip ci]
# [10.25.0](https://github.com/harttle/liquidjs/compare/v10.24.0...v10.25.0) (2026-03-07)

### Bug Fixes

* path traversal vulnerability, [#851](https://github.com/harttle/liquidjs/issues/851) ([#855](https://github.com/harttle/liquidjs/issues/855)) ([3cd024d](https://github.com/harttle/liquidjs/commit/3cd024d652dc883c46307581e979fe32302adbac))

### Features

* export error types, resolving [#837](https://github.com/harttle/liquidjs/issues/837) ([#840](https://github.com/harttle/liquidjs/issues/840)) ([71aa1b1](https://github.com/harttle/liquidjs/commit/71aa1b1998a3a66e536af67c6ea8947a28616eaf))
2026-03-07 20:01:42 +00:00
Yang JunandGitHub c7a291b46b chore: update semantic-release dependencies (#861) 2026-03-08 04:00:26 +08:00
Yang JunandGitHub eb4683ee3f chore: update to NPM Trusted Release (#860) 2026-03-08 03:35:49 +08:00
Yang JunandGitHub f1fc573a65 docs: state differences regarding inspect array/hash, #852, #853 (#858) 2026-03-08 03:14:13 +08:00
allcontributors[bot]GitHuballcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
524cd92cfe docs: add peaktwilight as a contributor for code (#857)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2026-03-08 02:40:16 +08:00
allcontributors[bot]GitHuballcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
0d9e797889 docs: add MorielHarush as a contributor for code (#856)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2026-03-08 02:39:45 +08:00
3cd024d652 fix: path traversal vulnerability, #851 (#855)
* Fix Path Traversal fallback

* Update loader.ts

Fixed nested

* Update loader.ts

padding fix

* refactor: reuse root enforcing

* docs: update test case and docs

---------

Co-authored-by: MorielHarush <[email protected]>
2026-03-08 02:36:09 +08:00
Yang JunandGitHub 85233e0568 docs: update testmu sponsor link (#850) 2026-02-14 13:54:03 +08:00
Yang JunandGitHub 02403a1879 docs: Change LambdaTest to TestMu AI (#848) 2026-01-19 23:26:49 +08:00
Yang JunandGitHub 1c6316111d docs: update docs for operators (#847) 2026-01-10 22:09:10 +08:00
Yang JunandGitHub 71aa1b1998 feat: export error types, resolving #837 (#840) 2025-11-22 00:27:44 +08:00
allcontributors[bot]GitHuballcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
350f95c8f7 docs: add rongjiecomputer as a contributor for code (#835)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2025-11-11 13:59:45 +08:00
Loo Rong JieandGitHub 955b7971c0 Support having new line and other whitespace after include filename (#834) 2025-11-11 13:58:12 +08:00
allcontributors[bot]GitHuballcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
8686876067 docs: add immerrr as a contributor for doc (#831)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2025-10-31 09:35:15 +08:00
immerrr againandGitHub 3a02eb12bf docs: update tutorial on operators and precedence (#830) 2025-10-31 09:34:05 +08:00
semantic-release-bot 906707833e chore(release): 10.24.0 [skip ci]
# [10.24.0](https://github.com/harttle/liquidjs/compare/v10.23.0...v10.24.0) (2025-10-27)

### Features

* **filters:** Add base64_encode and base64_decode filters for Shopify compatibility ([#828](https://github.com/harttle/liquidjs/issues/828)) ([86fc135](https://github.com/harttle/liquidjs/commit/86fc135d9ec0137689faf150535b9315e75ecc30))
2025-10-27 14:53:37 +00:00
allcontributors[bot]GitHuballcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
a2da822cb8 docs: add rosomri as a contributor for code (#829)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2025-10-27 22:42:15 +08:00
Omri RosnerandGitHub 86fc135d9e feat(filters): Add base64_encode and base64_decode filters for Shopify compatibility (#828)
* feat(filters): add base64 encode and decode

* fix: use Object.defineProperty for cross-platform btoa/atob mocking

* docs(filters): update docs

* docs(filters): update version
2025-10-27 22:40:31 +08:00
Yang JunandGitHub 5d953132e8 docs: add lambdatest to sponsors (#826) 2025-10-26 15:00:27 +08:00
allcontributors[bot]GitHuballcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2858271c8f docs: add skynetigor as a contributor for code (#825)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2025-10-23 22:23:52 +08:00
semantic-release-bot d22945ed5f chore(release): 10.23.0 [skip ci]
# [10.23.0](https://github.com/harttle/liquidjs/compare/v10.22.0...v10.23.0) (2025-10-23)

### Features

* Export specific tokens as types ([#824](https://github.com/harttle/liquidjs/issues/824)) ([4f7d2fd](https://github.com/harttle/liquidjs/commit/4f7d2fd84a8884e1009b13346d331a99b9721149))
2025-10-23 13:38:41 +00:00
Ihor PanasiukandGitHub 4f7d2fd84a feat: Export specific tokens as types (#824)
* Export specific tokens as types

* Update index.ts
2025-10-23 21:37:20 +08:00
semantic-release-bot 597ce7305f chore(release): 10.22.0 [skip ci]
# [10.22.0](https://github.com/harttle/liquidjs/compare/v10.21.1...v10.22.0) (2025-10-06)

### Bug Fixes

* math filters coerce invalid string to 0, [#813](https://github.com/harttle/liquidjs/issues/813) ([#819](https://github.com/harttle/liquidjs/issues/819)) ([e8e502c](https://github.com/harttle/liquidjs/commit/e8e502c5854c9649bf7611a671a068dc260011d1))

### Features

* allow context access in liquidMethodMissing, [#808](https://github.com/harttle/liquidjs/issues/808) ([#820](https://github.com/harttle/liquidjs/issues/820)) ([e551288](https://github.com/harttle/liquidjs/commit/e55128850e507687f9d85a012fc3a72ac2550f3b))
2025-10-06 14:45:55 +00:00
Yang Jun d7fa8ba5f1 chore: update node version for release workflow 2025-10-06 22:44:24 +08:00
Yang JunandGitHub 1b356d350d chore: fix Github artifact name (#821) 2025-10-06 22:32:34 +08:00
Yang JunandGitHub e55128850e feat: allow context access in liquidMethodMissing, #808 (#820) 2025-10-06 18:34:08 +08:00
Yang JunandGitHub e8e502c585 fix: math filters coerce invalid string to 0, #813 (#819) 2025-10-06 18:31:43 +08:00
allcontributors[bot]GitHuballcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
b8bc4db46c docs: add StreakingMan as a contributor for doc (#812)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2025-08-13 19:15:43 +08:00
裸奔狂甩丁丁andGitHub 68d500c18a docs: operators.md zh-cn translation (#811) 2025-08-13 19:14:47 +08:00
semantic-release-bot de12359bfd chore(release): 10.21.1 [skip ci]
## [10.21.1](https://github.com/harttle/liquidjs/compare/v10.21.0...v10.21.1) (2025-05-14)

### Bug Fixes

* block.super with strictVariables, [#806](https://github.com/harttle/liquidjs/issues/806) ([#807](https://github.com/harttle/liquidjs/issues/807)) ([025c40f](https://github.com/harttle/liquidjs/commit/025c40f0f2f13efa62193c61d2fa56943917ac3c))
2025-05-14 17:49:27 +00:00
Yang JunandGitHub 025c40f0f2 fix: block.super with strictVariables, #806 (#807) 2025-05-15 01:47:57 +08:00
Vlad GURDIGAandGitHub 2f414f8e40 docs: Fix formatting bug in echo.md (#805)
DISCLAIMER: This may not be the proper way to approach the issue.

Although the Markdown code is proper, on the website itself it is incorrectly rendered as "{{` and `}}".

The reason for the disclaimer above is that I’m imagining this may be an issue at the content rendering level, and my fix here is just a workaround of that issue. — Given this, I’ll not be offended if this PR of mine is rejected and closed. 🙂
2025-05-10 20:35:07 +08:00
Vlad GURDIGAandGitHub 40c52124d7 docs: Fix typo in options.md (#802)
Looks like just a typo.
2025-05-09 21:16:08 +08:00
allcontributors[bot]GitHuballcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
ae0c07e60b docs: add gurdiga as a contributor for doc (#804)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2025-05-09 20:37:59 +08:00
Vlad GURDIGAandGitHub 3b9202465e docs: A lil Markdown fix (#803)
Replaced square brackets with round ones in a link markup.
2025-05-09 20:36:49 +08:00
Harttle fc42ad7548 docs: update financial contributors 2025-04-03 21:27:48 +08:00
allcontributors[bot]andGitHub 050a7fc68e docs: add edh649 as a contributor for doc (#801) 2025-04-02 21:02:42 +08:00
Ed HantonandYang Jun 0fdc5c79da Update register-filters-tags.md
Improve documentation
2025-04-02 21:01:20 +08:00
semantic-release-bot 90d2ecb107 chore(release): 10.21.0 [skip ci]
# [10.21.0](https://github.com/harttle/liquidjs/compare/v10.20.3...v10.21.0) (2025-02-23)

### Features

* add find_index, has, and reject filters ([#799](https://github.com/harttle/liquidjs/issues/799)) ([0deb93e](https://github.com/harttle/liquidjs/commit/0deb93eeae4f530901e9a7d099bcc47207ad7385))
2025-02-23 14:59:29 +00:00
Bruno CarvalhoandGitHub 0deb93eeae feat: add find_index, has, and reject filters (#799)
* feat: add find_index, has, and reject filters

* Minor tweaks

* Change semantics of jekyllStyle, add more tests

* Some docs improvements
2025-02-23 22:57:17 +08:00
semantic-release-bot b0facc71f7 chore(release): 10.20.3 [skip ci]
## [10.20.3](https://github.com/harttle/liquidjs/compare/v10.20.2...v10.20.3) (2025-02-09)

### Bug Fixes

* empty tagToken.args since 10.20.0, fixes [#796](https://github.com/harttle/liquidjs/issues/796) ([38a0f51](https://github.com/harttle/liquidjs/commit/38a0f510b0a14baf35a368e9f07b536253394d06))
2025-02-09 14:51:09 +00:00
HarttleandYang Jun 5cb843f162 chore: migrate actions/upload-artifact to v4 2025-02-09 22:49:40 +08:00
HarttleandYang Jun 38a0f510b0 fix: empty tagToken.args since 10.20.0, fixes #796 2025-02-09 22:49:40 +08:00
Harttle 1a893f8023 docs: migrate to algolia app QJ35YOZTU4, #795 2025-02-09 22:12:04 +08:00
semantic-release-bot bf3bd54051 chore(release): 10.20.2 [skip ci]
## [10.20.2](https://github.com/harttle/liquidjs/compare/v10.20.1...v10.20.2) (2025-01-19)

### Bug Fixes

* consistent range syntax parsing, [#791](https://github.com/harttle/liquidjs/issues/791) ([a490a70](https://github.com/harttle/liquidjs/commit/a490a70da1ca2b479065c6618207bf4789db6b4f))
* context for group_by_exp/where_exp/find_exp, [#790](https://github.com/harttle/liquidjs/issues/790) ([a5070af](https://github.com/harttle/liquidjs/commit/a5070af3e4b4d1ae3b6398c6638b130e50e1cf6e))
2025-01-19 09:59:48 +00:00
HarttleandJun Yang a490a70da1 fix: consistent range syntax parsing, #791 2025-01-19 17:58:00 +08:00
HarttleandJun Yang a5070af3e4 fix: context for group_by_exp/where_exp/find_exp, #790 2025-01-19 17:53:25 +08:00
semantic-release-bot b070594fc7 chore(release): 10.20.1 [skip ci]
## [10.20.1](https://github.com/harttle/liquidjs/compare/v10.20.0...v10.20.1) (2025-01-04)

### Bug Fixes

* break/continue stops whole template, [#783](https://github.com/harttle/liquidjs/issues/783) ([5f1a4cf](https://github.com/harttle/liquidjs/commit/5f1a4cfdc9d6bde31ce86ddc88b8f4bdf52f7893))
* enumerate plain objects in where/where_exp, [#785](https://github.com/harttle/liquidjs/issues/785) ([#788](https://github.com/harttle/liquidjs/issues/788)) ([25ef104](https://github.com/harttle/liquidjs/commit/25ef104446731f4b6cb3a2e78f4d3b99efb635f4))
* preserveTimezones support for RFC2822 date, [#784](https://github.com/harttle/liquidjs/issues/784) ([59cf3c0](https://github.com/harttle/liquidjs/commit/59cf3c08dbc5f2e5b109ffcb5375ae738b5ac386))
2025-01-04 15:42:58 +00:00
Jun YangandGitHub 25ef104446 fix: enumerate plain objects in where/where_exp, #785 (#788) 2025-01-04 23:41:25 +08:00
HarttleandJun Yang 59cf3c08db fix: preserveTimezones support for RFC2822 date, #784 2025-01-04 22:46:07 +08:00
HarttleandJun Yang 5f1a4cfdc9 fix: break/continue stops whole template, #783 2025-01-04 22:15:39 +08:00
semantic-release-bot 8c32ab4f42 chore(release): 10.20.0 [skip ci]
# [10.20.0](https://github.com/harttle/liquidjs/compare/v10.19.1...v10.20.0) (2024-12-28)

### Features

* `size`, `first`, `last` support arraylike objects, [#781](https://github.com/harttle/liquidjs/issues/781) ([35a8442](https://github.com/harttle/liquidjs/commit/35a84421a622b3a6657946b9395839da2b8e154a))
* static variable analysis ([#770](https://github.com/harttle/liquidjs/issues/770)) ([3492ff6](https://github.com/harttle/liquidjs/commit/3492ff63f40abb8ff8adb8b6b0ce29408f99e19b))
2024-12-28 13:53:20 +00:00
Harttle 94a6715667 docs: zh-cn translation for static analyze features 2024-12-28 21:49:29 +08:00
JamesandGitHub 3492ff63f4 feat: static variable analysis (#770)
* feat: static variable analysis

* Accept any iterable from `children`, `arguments`, etc.

* Test analysis of standard tags

* Use `TagToken.tokenizer` instead of creating a new one

* Test analysis of netsted tags

* Group variables by their root value

* Test analysis of nested globals and locals

* Analyze included and rendered templates WIP

* Use existing tokenizer when constructing `Hash`

* Improve test coverage

* Analyze variables from `layout` and `block` tags

* Test analysis of Jekyll style includes

* Handle variables that start with a nested variable

* Async analysis

* Test non-standard tag end to end

* Implement convenience analysis methods on the `Liquid` class

* More analysis convenience methods

* Accept string or template array

* Draft static analysis docs

* Deduplicate variables names

* Fix isolated scope global variable map

* Coerce variables to strings instead of extending String

* Private map instead of extending Map

* Fix e2e test

* Tentatively implement analysis of aliased variables

* Fix nested variable segments array

* Update docs sidebar
2024-12-28 21:35:28 +08:00
HarttleandJun Yang 35a84421a6 feat: size, first, last support arraylike objects, #781 2024-12-28 16:10:06 +08:00
semantic-release-bot bb08cfab1f chore(release): 10.19.1 [skip ci]
## [10.19.1](https://github.com/harttle/liquidjs/compare/v10.19.0...v10.19.1) (2024-12-22)

### Bug Fixes

* add sideEffects=false to package.json ([734eb52](https://github.com/harttle/liquidjs/commit/734eb52b987d46d33cf8f03281a3773a0f1f0e4a))
* inconsistent continue behaviour, fixes [#779](https://github.com/harttle/liquidjs/issues/779) ([e3ef574](https://github.com/harttle/liquidjs/commit/e3ef574674c5a21a37b3ffc929f514c8a3d0b866))
* memoryLimit doesn't work in for tag, [#776](https://github.com/harttle/liquidjs/issues/776) ([2af297f](https://github.com/harttle/liquidjs/commit/2af297f81ac465feb3277ba7b92f7236409370b0))
2024-12-22 08:33:44 +00:00
HarttleandJun Yang e3ef574674 fix: inconsistent continue behaviour, fixes #779 2024-12-22 16:32:08 +08:00
359 changed files with 17855 additions and 11861 deletions
+145 -1
View File
@@ -14,7 +14,7 @@
"login": "harttle",
"name": "Jun Yang",
"avatar_url": "https://avatars3.githubusercontent.com/u/4427974?v=4",
"profile": "https://harttle.land",
"profile": "https://github.com/harttle",
"contributions": [
"maintenance",
"code"
@@ -721,6 +721,150 @@
"contributions": [
"code"
]
},
{
"login": "edh649",
"name": "Ed Hanton",
"avatar_url": "https://avatars.githubusercontent.com/u/527604?v=4",
"profile": "https://github.com/edh649",
"contributions": [
"doc"
]
},
{
"login": "gurdiga",
"name": "Vlad GURDIGA",
"avatar_url": "https://avatars.githubusercontent.com/u/53922?v=4",
"profile": "https://gurdiga.com",
"contributions": [
"doc"
]
},
{
"login": "StreakingMan",
"name": "裸奔狂甩丁丁",
"avatar_url": "https://avatars.githubusercontent.com/u/30397306?v=4",
"profile": "https://www.streakingman.com",
"contributions": [
"doc"
]
},
{
"login": "skynetigor",
"name": "Ihor Panasiuk",
"avatar_url": "https://avatars.githubusercontent.com/u/20903171?v=4",
"profile": "https://github.com/skynetigor",
"contributions": [
"code"
]
},
{
"login": "rosomri",
"name": "Omri Rosner",
"avatar_url": "https://avatars.githubusercontent.com/u/68001413?v=4",
"profile": "https://github.com/rosomri",
"contributions": [
"code"
]
},
{
"login": "immerrr",
"name": "immerrr again",
"avatar_url": "https://avatars.githubusercontent.com/u/579798?v=4",
"profile": "https://github.com/immerrr",
"contributions": [
"doc"
]
},
{
"login": "rongjiecomputer",
"name": "Loo Rong Jie",
"avatar_url": "https://avatars.githubusercontent.com/u/13115060?v=4",
"profile": "https://github.com/rongjiecomputer",
"contributions": [
"code"
]
},
{
"login": "MorielHarush",
"name": "MorielHarush",
"avatar_url": "https://avatars.githubusercontent.com/u/93482738?v=4",
"profile": "https://github.com/MorielHarush",
"contributions": [
"code"
]
},
{
"login": "peaktwilight",
"name": "Peak Twilight",
"avatar_url": "https://avatars.githubusercontent.com/u/77903714?v=4",
"profile": "https://doruk.ch",
"contributions": [
"code"
]
},
{
"login": "joecottam",
"name": "Joe Cottam",
"avatar_url": "https://avatars.githubusercontent.com/u/44173086?v=4",
"profile": "https://github.com/joecottam",
"contributions": [
"code"
]
},
{
"login": "timbze",
"name": "Timmy Braun",
"avatar_url": "https://avatars.githubusercontent.com/u/35117769?v=4",
"profile": "https://github.com/timbze",
"contributions": [
"code"
]
},
{
"login": "talboren",
"name": "Tal",
"avatar_url": "https://avatars.githubusercontent.com/u/68807791?v=4",
"profile": "https://github.com/talboren",
"contributions": [
"code"
]
},
{
"login": "VladimirFilonov",
"name": "Vladimir Filonov",
"avatar_url": "https://avatars.githubusercontent.com/u/813224?v=4",
"profile": "https://filonov.dev",
"contributions": [
"code"
]
},
{
"login": "spokodev",
"name": "spokodev",
"avatar_url": "https://avatars.githubusercontent.com/u/239690017?v=4",
"profile": "https://github.com/spokodev",
"contributions": [
"code"
]
},
{
"login": "YacovGold",
"name": "YacovGold",
"avatar_url": "https://avatars.githubusercontent.com/u/8984042?v=4",
"profile": "https://github.com/YacovGold",
"contributions": [
"code"
]
},
{
"login": "sarathfrancis90",
"name": "Sarath Francis",
"avatar_url": "https://avatars.githubusercontent.com/u/9289498?v=4",
"profile": "https://github.com/sarathfrancis90",
"contributions": [
"code"
]
}
],
"contributorsPerLine": 7,
+3 -3
View File
@@ -28,13 +28,13 @@ jobs:
- name: Build
run: npm run build
- name: Archive artifacts
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: dist-${{ inputs.os }}
path: dist
- name: Archive npm failure logs
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
if: failure()
with:
name: npm-logs
name: npm-logs-${{ inputs.os }}
path: ~/.npm/_logs
+1 -1
View File
@@ -22,7 +22,7 @@ jobs:
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Archive npm failure logs
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
if: failure()
with:
name: npm-logs
+1 -1
View File
@@ -24,7 +24,7 @@ jobs:
branch: gh-pages
folder: docs/public
- name: Archive npm failure logs
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
if: failure()
with:
name: npm-logs
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
- name: Lint
run: npm run lint
- name: Archive npm failure logs
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
if: failure()
with:
name: npm-logs
+2 -2
View File
@@ -19,14 +19,14 @@ jobs:
with:
node-version: '20'
- name: Download artifacts
uses: actions/download-artifact@v3
uses: actions/download-artifact@v4
with:
name: dist-${{ inputs.os }}
path: dist
- name: Check Performance
run: npm run perf:diff
- name: Archive npm failure logs
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
if: failure()
with:
name: npm-logs
+7 -2
View File
@@ -4,6 +4,11 @@ jobs:
release:
name: Release
runs-on: ubuntu-latest
permissions:
contents: write
issues: write
pull-requests: write
id-token: write
steps:
- name: Checkout
uses: actions/checkout@v3
@@ -12,7 +17,7 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '14'
node-version: '22'
- name: Install Dependencies
run: npm ci
- name: Release
@@ -26,7 +31,7 @@ jobs:
npx semantic-release --dry-run
fi
- name: Archive npm failure logs
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
if: failure()
with:
name: npm-logs
+12 -12
View File
@@ -14,13 +14,13 @@ jobs:
node-versoin: 22
- os: ubuntu-latest
timezone: Etc/GMT
node-version: 20
- os: ubuntu-latest
timezone: Asia/Shanghai
node-version: 18
- os: ubuntu-latest
timezone: Asia/Shanghai
node-version: 16
- os: ubuntu-latest
timezone: Asia/Shanghai
node-version: 15
- os: ubuntu-latest
timezone: Asia/Shanghai
node-version: 14
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
@@ -34,17 +34,17 @@ jobs:
- name: Install dependencies
run: npm ci
- name: Download artifacts
uses: actions/download-artifact@v3
uses: actions/download-artifact@v4
with:
name: dist-${{ matrix.os }}
path: dist
- name: Run Test
run: TZ=${{ matrix.timezone }} npm test
- name: Archive npm failure logs
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
if: failure()
with:
name: npm-logs
name: test-npm-logs-${{ matrix.os }}-${{ matrix.node-version }}
path: ~/.npm/_logs
demo:
name: Demo Check
@@ -59,15 +59,15 @@ jobs:
with:
node-version: 22
- name: Download artifacts
uses: actions/download-artifact@v3
uses: actions/download-artifact@v4
with:
name: dist-ubuntu-latest
path: dist
- name: Run Demo Test
run: npm run test:demo
- name: Archive npm failure logs
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
if: failure()
with:
name: npm-logs
name: demo-npm-logs
path: ~/.npm/_logs
+3 -1
View File
@@ -11,9 +11,11 @@ coverage/
node_modules/
# tmp
docs/public/js/liquid.browser.min.js
.local/
docs/themes/navy/source/js/liquid.browser.min.js
docs/themes/navy/layout/partial/all-contributors.swig
docs/themes/navy/layout/partial/financial-contributors.swig
docs/themes/navy/layout/partial/used-by.swig
dist/
demo/*/yarn.json
+94
View File
@@ -0,0 +1,94 @@
# LiquidJS
A simple, expressive, extensible Liquid template engine for JavaScript — Shopify, Jekyll and GitHub Pages compatible, for Node.js, browsers, and the CLI, with TypeScript support. TypeScript in `src/`, bundles in `dist/`. Docs site in `docs/` (Hexo, `navy` theme).
## Layout
| Path | Contents |
| --- | --- |
| `src/parser`, `src/render`, `src/tags`, `src/filters` | Template parse and render |
| `src/context`, `src/template`, `src/tokens` | Scope, templates, token stream |
| `src/util/async.ts` | `toPromise`, `toValueSync`, `toLiquidAsync` |
| `test/` | Jest |
| `docs/source/` | Doc markdown; sidebar in `docs/source/_data/sidebar.yml` |
| `docs/themes/navy/` | Layout, CSS, JS |
| `.local/` | Scratch, repro, PoC (gitignored) |
## Commands
```
npm run build # after src/ changes, before npm test
npm test
npm run lint
npm run check # build + build:docs + test + lint + perf:diff (manual)
npm run build:docs
cd docs && npm start # http://localhost:4000
npm run perf:diff
```
PR CI (`pull_request`): build, lint, test, coverage, performance. Docs build runs on push to `master` only.
PR titles: conventional format (`feat:`, `fix:`, `docs:`, …) — checked by CI. Releases on `master` use semantic-release from merged commits.
Backward-compatible API changes expected unless doing an intentional major break.
## Architecture
All core logic is one `function *` per feature. Use `yield` where you'd normally `await` a potentially async value.
- `toPromise(generator)` — async driver; awaits yielded promises
- `toValueSync(generator)` — sync driver; passes yielded values through as-is
Never duplicate logic into separate async and sync methods. One generator serves both paths.
When wrapping an async+sync pair (e.g. `contains`/`containsSync`, `readFile`/`readFileSync`), use `toLiquidAsync(asyncFn, syncFn?)` — returns a `LiquidAsync<F>` that picks sync or async via a leading `sync: boolean` arg. `yield` the result inside a generator. See `src/util/async.ts`.
## Style
Make minimal changes only. Avoid sweeping edits. Always check after you made changes.
- Change only what the task requires. No drive-by refactors, test harnesses, or extra files unless asked.
- Match existing patterns in the file you edit.
- Repro, PoC, and scratch files go in `.local/` — not tracked `poc/` folders or one-off scripts under `docs/`.
### Comments
- Do not add narrative comments. Code should be clear from structure and naming; if it needs explanation, refactor instead.
- Comments follow existing repo usage only: non-obvious invariants, `@deprecated`, JSDoc on public API where TypeDoc needs it. Not for explaining changes to the author, migration history, or restating what the code already says.
- Comments document the code; they do not fix unclear code.
### Tests
- Assert observable behavior, not internal implementation details.
- Avoid duplicate coverage; keep test diffs minimal.
- **E2E** (`test/e2e/`): import from the package root (resolves to `dist/` via `package.json`). Do not import from `src/` — e2e must match what npm consumers get.
- **Integration/unit** (`test/integration/`, etc.): may import from `src/` against current TypeScript sources.
### Docs site
- Reuse existing asset paths under `docs/source/` and `docs/themes/navy/` — no new asset directories unless asked.
- Front matter `title:` is plain text (no backticks).
- `docs/source/llms.txt` — deployed to https://liquidjs.com/llms.txt for web agents (llms.txt spec).
- After theme/markdown changes: build or serve locally, check in a browser (light and dark), not only curl or editor preview.
### README
- Research original sources before reordering contributors, logos, or lists.
## Verify
- Do not commit, push, amend, or open a PR unless asked.
- After changes: verify yourself via CLI or UI (tests, `cd docs && npm start`, browser) before reporting done. Do not tell the user to check instead.
- Before push on sweeping changes: run `npm run check`.
- Confirm facts from `.github/workflows`, `package.json`, and library docs — not stale human docs or assumptions.
- When replacing or integrating a library: read its docs and understand what the previous setup did before changing behavior.
### Security fixes
- Reproduce on current `master` first. Smallest fix that addresses the reported issue.
- If Shopify/Ruby Liquid behaves the same, document unsafe usage in filter/docs instead of changing behavior.
## Docs
- Published: https://liquidjs.com
- Repo agent instructions: this file (`AGENTS.md`)
+215
View File
@@ -1,3 +1,218 @@
# [10.29.0](https://github.com/harttle/liquidjs/compare/v10.28.0...v10.29.0) (2026-08-11)
### Features
* add unregisterFilter method ([#946](https://github.com/harttle/liquidjs/issues/946)) ([69b2c58](https://github.com/harttle/liquidjs/commit/69b2c589f9b69a34427cb8533ddb938bd997914f))
* **filters:** add squish filter ([#943](https://github.com/harttle/liquidjs/issues/943)) ([875513f](https://github.com/harttle/liquidjs/commit/875513f4c5136bed0c64562cccabb21a7db8d36c))
# [10.28.0](https://github.com/harttle/liquidjs/compare/v10.27.2...v10.28.0) (2026-08-01)
### Bug Fixes
* **date:** %s returns Unix epoch unaffected by display timezone ([#932](https://github.com/harttle/liquidjs/issues/932)) ([39c8743](https://github.com/harttle/liquidjs/commit/39c87437c5ef38ede9a208c9d55cd13231c6c023)), closes [#931](https://github.com/harttle/liquidjs/issues/931)
### Features
* Add support of inner expressions enclosed by parentheses ([#863](https://github.com/harttle/liquidjs/issues/863)) ([afa5f54](https://github.com/harttle/liquidjs/commit/afa5f5400428fc1ec935aca0282e579224660c95))
## [10.27.2](https://github.com/harttle/liquidjs/compare/v10.27.1...v10.27.2) (2026-07-09)
### Bug Fixes
* charge join/json/inspect filters by produced output size ([#925](https://github.com/harttle/liquidjs/issues/925)) ([7ab49f9](https://github.com/harttle/liquidjs/commit/7ab49f999ac045ec1e87f3a7a9fd68dd9e8602b3))
* **date:** zero-pad milliseconds when formatting %N fractional seconds ([#929](https://github.com/harttle/liquidjs/issues/929)) ([2634f9d](https://github.com/harttle/liquidjs/commit/2634f9de7b1228cd887b7cab880af8a795c77053))
* enforce ownPropertyOnly for inherited array indices ([#924](https://github.com/harttle/liquidjs/issues/924)) ([552819a](https://github.com/harttle/liquidjs/commit/552819a84b80c62306fe61072628a756272dc749))
* **filters:** modulo should follow divisor sign for negative operands ([#922](https://github.com/harttle/liquidjs/issues/922)) ([568bd5f](https://github.com/harttle/liquidjs/commit/568bd5f9cb99f596292c09fd70b00284b8216f0c))
* **filters:** return empty for out-of-range slice begin or negative length ([#928](https://github.com/harttle/liquidjs/issues/928)) ([f9a1316](https://github.com/harttle/liquidjs/commit/f9a1316d161f4f20018c833160f42dfcf0cde507))
## [10.27.1](https://github.com/harttle/liquidjs/compare/v10.27.0...v10.27.1) (2026-06-23)
### Bug Fixes
* improve round function; improvement to [#873](https://github.com/harttle/liquidjs/issues/873) ([#901](https://github.com/harttle/liquidjs/issues/901)) ([956b51e](https://github.com/harttle/liquidjs/commit/956b51ea953eb52d9eba7409b7f51e379023fec4))
* **security:** charge pop filter allocation to memoryLimit ([#907](https://github.com/harttle/liquidjs/issues/907)) ([8a0c74a](https://github.com/harttle/liquidjs/commit/8a0c74a7fcb1671aa1dcb71ec82ba0602dc90d04))
* **strip_html:** infinite loop for strip_html ([5c3522f](https://github.com/harttle/liquidjs/commit/5c3522f33928aae66f0fe85c36e1d9015c768fe2))
### Performance Improvements
* **parser:** memoize createTrie to avoid rebuilding tries per Tokenizer ([#911](https://github.com/harttle/liquidjs/issues/911)) ([3a0d80d](https://github.com/harttle/liquidjs/commit/3a0d80d1f4526af0fbca2bb2e0a9c51669d2fd3e))
# [10.27.0](https://github.com/harttle/liquidjs/compare/v10.26.0...v10.27.0) (2026-05-15)
### Features
* **context:** null-prototype scope frames via createScope ([#899](https://github.com/harttle/liquidjs/issues/899)) ([47d3f1b](https://github.com/harttle/liquidjs/commit/47d3f1b1cf33be91fe587821f288d1c9d8e1ace7))
# [10.26.0](https://github.com/harttle/liquidjs/compare/v10.25.7...v10.26.0) (2026-05-14)
### Bug Fixes
* **date:** cap strftime widths and account padding in memoryLimit ([#895](https://github.com/harttle/liquidjs/issues/895)) ([3129d46](https://github.com/harttle/liquidjs/commit/3129d46dc95efa357b00e5a57ee1af80a13d72ed))
* enforce renderLimit for empty renderTemplates calls ([#894](https://github.com/harttle/liquidjs/issues/894)) ([5b9c346](https://github.com/harttle/liquidjs/commit/5b9c3469085e01c79e2d0af28e2a13f730e1793d))
* propagate ownPropertyOnly into Context.spawn() for {% render %} ([#893](https://github.com/harttle/liquidjs/issues/893)) ([dbbf628](https://github.com/harttle/liquidjs/commit/dbbf6288030591bf6da28d8c1cce5a17bca97bb6))
* **security:** block Object.prototype filter/tag lookups (RCE) ([#897](https://github.com/harttle/liquidjs/issues/897)) ([457fae0](https://github.com/harttle/liquidjs/commit/457fae0736c3ec862539b9dbf7f477e6c08fb6c6))
* strip html newline tags ([#892](https://github.com/harttle/liquidjs/issues/892)) ([26ea285](https://github.com/harttle/liquidjs/commit/26ea2856c7a90aec892b98d94a9b7a3e18539045))
* **strip_html:** rewrite as linear single-pass scan to avoid ReDoS ([#896](https://github.com/harttle/liquidjs/issues/896)) ([3616a74](https://github.com/harttle/liquidjs/commit/3616a744b9abeb425c217b340a2397d46176afb8))
### Features
* add sha256 and hmac_sha256 filters for cryptographic operations ([#889](https://github.com/harttle/liquidjs/issues/889)) ([1c816d4](https://github.com/harttle/liquidjs/commit/1c816d4fc3bcd2cba011f7a84f56a4251fca0622))
## [10.25.7](https://github.com/harttle/liquidjs/compare/v10.25.6...v10.25.7) (2026-04-23)
### Bug Fixes
* **filters:** support Buffer input in base64_encode to prevent binary data corruption ([#881](https://github.com/harttle/liquidjs/issues/881)) ([0ee6dbb](https://github.com/harttle/liquidjs/commit/0ee6dbb511aa926f6d490293282060abf3bab37f))
## [10.25.6](https://github.com/harttle/liquidjs/compare/v10.25.5...v10.25.6) (2026-04-19)
### Bug Fixes
* nested block for layout ([#883](https://github.com/harttle/liquidjs/issues/883)) ([e2311df](https://github.com/harttle/liquidjs/commit/e2311dfd6e82f73509308aa8a3a1fafc92e226f0))
## [10.25.5](https://github.com/harttle/liquidjs/compare/v10.25.4...v10.25.5) (2026-04-07)
### Bug Fixes
* enforce root containment for renderFile/parseFile lookups ([#870](https://github.com/harttle/liquidjs/issues/870)) ([f41c1fc](https://github.com/harttle/liquidjs/commit/f41c1fc02fe901598f3328118b42b13bc6bc9b04))
* null date should return empty ([#868](https://github.com/harttle/liquidjs/issues/868)) ([#872](https://github.com/harttle/liquidjs/issues/872)) ([4f9a499](https://github.com/harttle/liquidjs/commit/4f9a49988a93c156524981e189a4fec238e682b8))
* rounding negative away from zero when half ([#873](https://github.com/harttle/liquidjs/issues/873)) ([1cdf10b](https://github.com/harttle/liquidjs/commit/1cdf10b57d82f0592414efbfca19e204b37aea9f))
## [10.25.4](https://github.com/harttle/liquidjs/compare/v10.25.3...v10.25.4) (2026-04-07)
### Bug Fixes
* sort and sort_natural filters bypass ownPropertyOnly ([#869](https://github.com/harttle/liquidjs/issues/869)) ([e743da0](https://github.com/harttle/liquidjs/commit/e743da0020d34e2ee547e1cc1a86b58377ebe1ce))
## [10.25.3](https://github.com/harttle/liquidjs/compare/v10.25.2...v10.25.3) (2026-04-06)
### Bug Fixes
* precise memoryLimit for string replace ([abc058b](https://github.com/harttle/liquidjs/commit/abc058be0f33d6372cd2216f4945183167abeb25))
* use realpath for fs.contains ([#867](https://github.com/harttle/liquidjs/issues/867)) ([529dd67](https://github.com/harttle/liquidjs/commit/529dd67eeb6b125637623d6a723601f0938d3613))
## [10.25.2](https://github.com/harttle/liquidjs/compare/v10.25.1...v10.25.2) (2026-03-25)
### Bug Fixes
* handle undefined replacement argument in replace filter ([#864](https://github.com/harttle/liquidjs/issues/864)) ([0ad2b11](https://github.com/harttle/liquidjs/commit/0ad2b11ab15e7da608a9ef936b2a00a6a6517038))
## [10.25.1](https://github.com/harttle/liquidjs/compare/v10.25.0...v10.25.1) (2026-03-22)
### Bug Fixes
* mem limiter for invalid ranges ([95ddefc](https://github.com/harttle/liquidjs/commit/95ddefc056a11a44d9e753fd47a39db2c241e578))
* treat args for replace_first as literal ([35d5230](https://github.com/harttle/liquidjs/commit/35d523026345d80458df24c72e653db78b5d061d))
# [10.25.0](https://github.com/harttle/liquidjs/compare/v10.24.0...v10.25.0) (2026-03-07)
### Bug Fixes
* path traversal vulnerability, [#851](https://github.com/harttle/liquidjs/issues/851) ([#855](https://github.com/harttle/liquidjs/issues/855)) ([3cd024d](https://github.com/harttle/liquidjs/commit/3cd024d652dc883c46307581e979fe32302adbac))
### Features
* export error types, resolving [#837](https://github.com/harttle/liquidjs/issues/837) ([#840](https://github.com/harttle/liquidjs/issues/840)) ([71aa1b1](https://github.com/harttle/liquidjs/commit/71aa1b1998a3a66e536af67c6ea8947a28616eaf))
# [10.24.0](https://github.com/harttle/liquidjs/compare/v10.23.0...v10.24.0) (2025-10-27)
### Features
* **filters:** Add base64_encode and base64_decode filters for Shopify compatibility ([#828](https://github.com/harttle/liquidjs/issues/828)) ([86fc135](https://github.com/harttle/liquidjs/commit/86fc135d9ec0137689faf150535b9315e75ecc30))
# [10.23.0](https://github.com/harttle/liquidjs/compare/v10.22.0...v10.23.0) (2025-10-23)
### Features
* Export specific tokens as types ([#824](https://github.com/harttle/liquidjs/issues/824)) ([4f7d2fd](https://github.com/harttle/liquidjs/commit/4f7d2fd84a8884e1009b13346d331a99b9721149))
# [10.22.0](https://github.com/harttle/liquidjs/compare/v10.21.1...v10.22.0) (2025-10-06)
### Bug Fixes
* math filters coerce invalid string to 0, [#813](https://github.com/harttle/liquidjs/issues/813) ([#819](https://github.com/harttle/liquidjs/issues/819)) ([e8e502c](https://github.com/harttle/liquidjs/commit/e8e502c5854c9649bf7611a671a068dc260011d1))
### Features
* allow context access in liquidMethodMissing, [#808](https://github.com/harttle/liquidjs/issues/808) ([#820](https://github.com/harttle/liquidjs/issues/820)) ([e551288](https://github.com/harttle/liquidjs/commit/e55128850e507687f9d85a012fc3a72ac2550f3b))
## [10.21.1](https://github.com/harttle/liquidjs/compare/v10.21.0...v10.21.1) (2025-05-14)
### Bug Fixes
* block.super with strictVariables, [#806](https://github.com/harttle/liquidjs/issues/806) ([#807](https://github.com/harttle/liquidjs/issues/807)) ([025c40f](https://github.com/harttle/liquidjs/commit/025c40f0f2f13efa62193c61d2fa56943917ac3c))
# [10.21.0](https://github.com/harttle/liquidjs/compare/v10.20.3...v10.21.0) (2025-02-23)
### Features
* add find_index, has, and reject filters ([#799](https://github.com/harttle/liquidjs/issues/799)) ([0deb93e](https://github.com/harttle/liquidjs/commit/0deb93eeae4f530901e9a7d099bcc47207ad7385))
## [10.20.3](https://github.com/harttle/liquidjs/compare/v10.20.2...v10.20.3) (2025-02-09)
### Bug Fixes
* empty tagToken.args since 10.20.0, fixes [#796](https://github.com/harttle/liquidjs/issues/796) ([38a0f51](https://github.com/harttle/liquidjs/commit/38a0f510b0a14baf35a368e9f07b536253394d06))
## [10.20.2](https://github.com/harttle/liquidjs/compare/v10.20.1...v10.20.2) (2025-01-19)
### Bug Fixes
* consistent range syntax parsing, [#791](https://github.com/harttle/liquidjs/issues/791) ([a490a70](https://github.com/harttle/liquidjs/commit/a490a70da1ca2b479065c6618207bf4789db6b4f))
* context for group_by_exp/where_exp/find_exp, [#790](https://github.com/harttle/liquidjs/issues/790) ([a5070af](https://github.com/harttle/liquidjs/commit/a5070af3e4b4d1ae3b6398c6638b130e50e1cf6e))
## [10.20.1](https://github.com/harttle/liquidjs/compare/v10.20.0...v10.20.1) (2025-01-04)
### Bug Fixes
* break/continue stops whole template, [#783](https://github.com/harttle/liquidjs/issues/783) ([5f1a4cf](https://github.com/harttle/liquidjs/commit/5f1a4cfdc9d6bde31ce86ddc88b8f4bdf52f7893))
* enumerate plain objects in where/where_exp, [#785](https://github.com/harttle/liquidjs/issues/785) ([#788](https://github.com/harttle/liquidjs/issues/788)) ([25ef104](https://github.com/harttle/liquidjs/commit/25ef104446731f4b6cb3a2e78f4d3b99efb635f4))
* preserveTimezones support for RFC2822 date, [#784](https://github.com/harttle/liquidjs/issues/784) ([59cf3c0](https://github.com/harttle/liquidjs/commit/59cf3c08dbc5f2e5b109ffcb5375ae738b5ac386))
# [10.20.0](https://github.com/harttle/liquidjs/compare/v10.19.1...v10.20.0) (2024-12-28)
### Features
* `size`, `first`, `last` support arraylike objects, [#781](https://github.com/harttle/liquidjs/issues/781) ([35a8442](https://github.com/harttle/liquidjs/commit/35a84421a622b3a6657946b9395839da2b8e154a))
* static variable analysis ([#770](https://github.com/harttle/liquidjs/issues/770)) ([3492ff6](https://github.com/harttle/liquidjs/commit/3492ff63f40abb8ff8adb8b6b0ce29408f99e19b))
## [10.19.1](https://github.com/harttle/liquidjs/compare/v10.19.0...v10.19.1) (2024-12-22)
### Bug Fixes
* add sideEffects=false to package.json ([734eb52](https://github.com/harttle/liquidjs/commit/734eb52b987d46d33cf8f03281a3773a0f1f0e4a))
* inconsistent continue behaviour, fixes [#779](https://github.com/harttle/liquidjs/issues/779) ([e3ef574](https://github.com/harttle/liquidjs/commit/e3ef574674c5a21a37b3ffc929f514c8a3d0b866))
* memoryLimit doesn't work in for tag, [#776](https://github.com/harttle/liquidjs/issues/776) ([2af297f](https://github.com/harttle/liquidjs/commit/2af297f81ac465feb3277ba7b92f7236409370b0))
# [10.19.0](https://github.com/harttle/liquidjs/compare/v10.18.0...v10.19.0) (2024-11-17)
+103 -67
View File
@@ -1,103 +1,117 @@
# liquidjs
# LiquidJS
A simple, expressive, extensible Liquid template engine for JavaScript — Shopify, Jekyll and GitHub Pages compatible, for Node.js, browsers, and the CLI, with TypeScript support.
[![npm version](https://img.shields.io/npm/v/liquidjs.svg?logo=npm&style=flat-square)](https://www.npmjs.org/package/liquidjs)
[![npm downloads](https://img.shields.io/npm/dm/liquidjs.svg?style=flat-square)](https://www.npmjs.org/package/liquidjs)
[![Coverage](https://img.shields.io/coveralls/harttle/liquidjs.svg?style=flat-square)](https://coveralls.io/github/harttle/liquidjs?branch=master)
[![Build Status](https://img.shields.io/github/actions/workflow/status/harttle/liquidjs/ci-build.yml?branch=master&style=flat-square)](https://github.com/harttle/liquidjs/actions/workflows/ci-build.yml?query=branch%3Amaster)
[![DUB license](https://img.shields.io/dub/l/vibe-d.svg?style=flat-square)](https://github.com/harttle/liquidjs/blob/master/LICENSE)
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg?style=flat-square)](https://github.com/harttle/liquidjs)
[![Coverage](https://img.shields.io/coveralls/harttle/liquidjs.svg?style=flat-square)](https://coveralls.io/github/harttle/liquidjs?branch=master)
[![License: MIT](https://img.shields.io/github/license/harttle/liquidjs?style=flat-square)](https://github.com/harttle/liquidjs/blob/master/LICENSE)
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 so that [Jekyll sites](https://jekyllrb.com), [GitHub Pages](https://pages.github.com/) and [Shopify templates](https://themes.shopify.com/) can be ported to Node.js without pain.
[Documentation][doc] · [Playground](https://liquidjs.com/playground.html) · [Setup guide][setup] · [Contributing][contribution]
* [Documentation][doc]
* Please star [LiquidJS on GitHub][github]!
* Financial support via [GitHub Sponsors](https://github.com/sponsors/harttle).
<a href="https://liquidjs.com/playground.html">
<img src="docs/source/playground-demo.gif" alt="LiquidJS playground: edit a template and context, see live HTML output" width="980" style="display: block; margin: 0 auto;" />
</a>
<p align="center"><a href="https://liquidjs.com"><img height="155px" width="155px" src="https://liquidjs.com/icon/mstile-310x310.png" alt="logo"></a></p>
<p align="center"><sub>Try the <a href="https://liquidjs.com/playground.html">online playground</a>.</sub></p>
## What's it like?
## Quick start
Basically there're two types of Liquid syntax: tags enclosed by `{% %}` and outputs enclosed by `{{ }}`. A Liquid template looks like:
```js
import { Liquid } from 'liquidjs'
```liquid
{% if username %}
{{ username | append: ", welcome to LiquidJS!" | capitalize }}
{% endif %}
const engine = new Liquid()
const html = await engine.parseAndRender(
'Hello, {{ name | capitalize }}!',
{ name: 'liquid' }
)
//=> 'Hello, Liquid!'
```
[A live demo](https://liquidjs.com/playground.html) is also available and here's a [quick tutorial](https://liquidjs.com/tutorials/intro-to-liquid.html) for Liquid syntax.
## Installation
Install from npm in Node.js:
**Node.js**
```bash
npm install liquidjs
```
Or use the UMD bundle from jsDelivr:
**Browser** (jsDelivr UMD bundle)
```html
<script src="https://cdn.jsdelivr.net/npm/liquidjs/dist/liquid.browser.min.js"></script>
```
Or render directly from CLI using npx:
**CLI**
```bash
npx liquidjs --template 'Hello, {{ name }}!' --context '{"name": "Snake"}'
npx liquidjs --template 'Hello, {{ name }}!' --context '{"name": "Liquid"}'
```
For more details, refer to the [Setup Guide][setup].
See the [setup guide][setup] for partials, layouts, caching, and other options.
## Who's Using LiquidJS?
## Used by
- [Eleventy](https://www.11ty.dev/): Eleventy, a simpler static site generator.
- [Opensense](https://www.opensense.com/): The smarter way to send email.
- [Directus](https://docs.directus.io/): an instant REST+GraphQL API and intuitive no-code data collaboration app for any SQL database.
- [Semgrep](https://github.com/returntocorp/semgrep): Lightweight static analysis for many languages.
- [Rock](https://www.rockrms.com/): An open source CMS, Relationship Management System (RMS) and Church Management System (ChMS) all rolled into one.
- [Mitosis](https://github.com/BuilderIO/mitosis): Write components once, run everywhere. Compiles to React, Vue, Qwik, Solid, Angular, Svelte, and more.
- [Pattern Lab](https://patternlab.io/): a frontend workshop environment that helps you build, view, test, and showcase your design system's UI components.
- [Builder.io](https://www.builder.io/m/developers): the first and only headless CMS with a visual editor that lets you drag and drop with your components, directly within your current site or app. Completely API-driven, for cleaner code and simpler workflows.
- [Microsoft Power Pages](https://learn.microsoft.com/en-us/power-pages/introduction): a secure, enterprise-grade, low-code software as a service (SaaS) platform for creating, hosting, and administering modern external-facing business websites.
- [Azure API Management developer portal](https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-developer-portal): an automatically generated, fully customizable website with the documentation of your APIs.
- [WISMOlabs](https://wismolabs.com/): Post Purchase Experience platform for eCommerce retailers enhancing customer satisfaction by using LiquidJS to provide customizable post-purchase experiences through programmable email, SMS, order tracking pages, and webhooks.
<!-- USED-BY-BEGIN -->
<p align="center" style="line-height: 2.5;">
<a href="https://www.11ty.dev/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/35147177?v=4&s=100" height="80" style="vertical-align: middle;" alt="Eleventy" title="Eleventy"/></a>
<a href="https://www.opensense.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/opensense-inc/bf840ae/logo/256.png?height=100" height="80" style="vertical-align: middle;" alt="Opensense" title="Opensense"/></a>
<a href="https://www.microsoft.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/6154722?v=4&s=100" height="80" style="vertical-align: middle;" alt="Power Pages, Azure API Management developer portal" title="Power Pages, Azure API Management developer portal"/></a>
<a href="https://docs.github.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/9919?v=4&amp;s=100" height="80" style="vertical-align: middle;" alt="GitHub Docs" title="GitHub Docs"/></a>
<a href="https://github.com/elastic/kibana" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/6764390?v=4&s=100" height="80" style="vertical-align: middle;" alt="Kibana" title="Kibana"/></a>
<a href="https://www.shopify.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/8085?v=4&amp;s=100" height="80" style="vertical-align: middle;" alt="Shopify CLI, Checkout Blocks" title="Shopify CLI, Checkout Blocks"/></a>
<a href="https://customer.io/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/1152079?v=4&s=100" height="80" style="vertical-align: middle;" alt="Customer IO" title="Customer IO"/></a>
<br/>
<a href="https://syntax.fm/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/130389858?v=4&s=100" height="80" style="vertical-align: middle;" alt="Syntax Podcast" title="Syntax Podcast"/></a>
<a href="https://www.testmuai.com/?utm_medium=sponsor&utm_source=liquidjs" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/27130435?s=200&v=4" width="80" style="vertical-align: middle;" alt="TestMu AI" title="TestMu AI"/></a>
<a href="https://chudovo.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/Chudovo/avatar/256.png?height=100" width="160" style="vertical-align: middle;background: white;padding: 8px 16px;" alt="Chudovo" title="Chudovo"/></a>
<a href="https://www.pakstyle.pk/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/pakstyle/2b81605/logo/256.png?height=100" height="80" style="vertical-align: middle;" alt="PakStyle.pk" title="PakStyle.pk"/></a>
<a href="https://www.escorta.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/escortacom/avatar/256.png?height=100" height="45" style="vertical-align: middle;" alt="EscortA.com" title="EscortA.com"/></a>
<a href="https://opencollective.com/touchless" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/touchless/273bc74/logo/256.png?height=100" height="80" style="vertical-align: middle;" alt="Touchless" title="Touchless"/></a>
<br/>
<a href="https://www.dropkiq.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/1bertlol/43a8ea8/logo/256.png?height=100" height="80" style="vertical-align: middle;" alt="Dropkiq" title="Dropkiq"/></a>
<a href="https://directus.io/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/15967950?v=4&amp;s=100" height="80" style="vertical-align: middle;" alt="Directus" title="Directus"/></a>
<a href="https://www.builder.io/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://cdn.builder.io/api/v1/image/assets%2FYJIGb4i01jvw0SRdL5Bt%2F51a002f4a17f4fc4a829b8891a1c25ee" height="80" style="vertical-align: middle;" alt="Builder.io, Mitosis" title="Builder.io, Mitosis"/></a>
<a href="https://patternlab.io/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/4733935?v=4&amp;s=100" height="80" style="vertical-align: middle;" alt="Pattern Lab" title="Pattern Lab"/></a>
<a href="https://www.rockrms.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://www.rockrms.com/GetImage.ashx?id=72533" height="80" style="vertical-align: middle;" alt="Rock RMS" title="Rock RMS"/></a>
<a href="https://wismolabs.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://cdn-ldlap.nitrocdn.com/DsLJMZpUUekfsitqBnNmsRAnzbwPoIzE/assets/images/optimized/rev-5df8687/wismolabs.com/wp-content/uploads/2023/03/favicon-300x300.png" height="80" style="vertical-align: middle;" alt="WISMOlabs" title="WISMOlabs"/></a>
<a href="https://chromewebstore.google.com/detail/freshet/mpclplhdencffbilobpcapccnihpelcg" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://raw.githubusercontent.com/MattAltermatt/freshet/main/public/icon-128.png" height="80" style="vertical-align: middle;" alt="Freshet" title="Freshet"/></a>
</p>
<!-- USED-BY-END -->
Feel free to create a PR or contact me to add your use case into this list!
Products and projects running on LiquidJS. [Open a PR](https://github.com/harttle/liquidjs/edit/master/README.md) to add yours.
## Financial Support
If you personally love LiquidJS or it's benefiting your business, please consider financially support us via [GitHub Sponsors](https://github.com/sponsors/harttle). Special thanks to our sponsors!
<!-- FINANCIAL-CONTRIBUTORS-BEGIN -->
<table>
<tbody>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://www.opensense.com/"><img src="https://images.opencollective.com/opensense-inc/bf840ae/logo/256.png?height=100" width="100px;" alt="Opensense Inc."/><br /><sub><b>Opensense</b></sub></a></td>
<td align="center" valign="top" width="14.28%"><a href="https://www.11ty.dev/"><img src="https://avatars.githubusercontent.com/u/35147177?v=4&s=100" width="100px;" alt="Eleventy"/><br /><sub><b>Eleventy</b></sub></a></td>
<td align="center" valign="top" width="14.28%"><a href="https://about.me/peterdehaan"><img src="https://avatars2.githubusercontent.com/u/557895?v=4&s=100" width="100px;" alt="Peter deHaan"/><br /><sub><b>Peter deHaan</b></sub></a></td>
<td align="center" valign="top" width="14.28%"><a href="https://opencollective.com/touchless"><img src="https://images.opencollective.com/touchless/273bc74/logo/256.png?height=100" width="100px;" alt="Touchless"/><br /><sub><b>Touchless</b></sub></a></td>
<td align="center" valign="top" width="14.28%"><a href="https://www.dropkiq.com/"><img src="https://images.opencollective.com/1bertlol/43a8ea8/logo/256.png?height=100" width="100px;" alt="Adam Darrah"/><br /><sub><b>Dropkiq</b></sub></a></td>
<td align="center" valign="top" width="14.28%"><a href="https://dailycontributors.com/"><img src="https://images.opencollective.com/dailycontributors/3c2e057/logo/256.png?height=100&width=100" width="100px;" alt="Dailycontributors"/><br /><sub><b>Dailycontributors</b></sub></a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/coni2k"><img src="https://avatars0.githubusercontent.com/u/1284601?v=4&s=100" width="100px;" alt="coni2k"/><br /><sub><b>Serkan Holat</b></sub></a></td>
</tr>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/amit777"><img src="https://avatars0.githubusercontent.com/u/2703309?v=4&s=100" width="100px;" alt="amit777"/><br /><sub><b>amit777</b></sub></a></td>
<td align="center" valign="top" width="14.28%"><a href="https://opencollective.com/khaled-salem"><img src="https://images.opencollective.com/khaled-salem/avatar/256.png?height=256" width="100px;" alt="Khaled Salem"/><br /><sub><b>Khaled Salem</b></sub></a></td>
<td align="center" valign="top" width="14.28%"><a href="https://sentry.io/"><img src="https://avatars.githubusercontent.com/u/1396951?v=4&s=100" width="100px;" alt="Sentry"/><br /><sub><b>Sentry</b></sub></a></td>
<td align="center" valign="top" width="14.28%"><a href="https://www.checkoutblocks.com/"><img src="https://avatars.githubusercontent.com/u/114603307?v=4&s=100" width="100px;" alt="Checkout Blocks"/><br /><sub><b>Checkout Blocks</b></sub></a></td>
<td align="center" valign="top" width="14.28%"><a href="https://customer.io/"><img src="https://avatars.githubusercontent.com/u/1152079?v=4&s=100" width="100px;" alt="Customer IO"/><br /><sub><b>Customer IO</b></sub></a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/15fathoms"><img src="https://avatars.githubusercontent.com/u/79156039?v=4&s=100" width="100px;" alt="Emmanuel Cartelli"/><br /><sub><b>Emmanuel Cartelli</b></sub></a><br /></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/microsoft"><img src="https://avatars.githubusercontent.com/u/6154722?v=4&s=100" width="100px;" alt="Microsoft"/><br /><sub><b>Microsoft</b></sub></a><br /></td>
</tr>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://www.pakstyle.pk/"><img src="https://images.opencollective.com/pakstyle/2b81605/logo/256.png?height=100" width="100px;" alt="PakStyle.pk"/><br /><sub><b>PakStyle.pk</b></sub></a></td>
<td align="center" valign="top" width="14.28%"><a href="https://syntax.fm/"><img src="https://avatars.githubusercontent.com/u/130389858?v=4&s=100" width="100px;" alt="Syntax Podcast"/><br /><sub><b>Syntax Podcast</b></sub></a></td>
<td align="center" valign="top" width="14.28%"><a href="https://opencollective.com/cartelli-emmanuel"><img src="https://images.opencollective.com/cartelli-emmanuel/avatar/256.png?height=100" width="100px;" alt="Cartelli Emmanuel"/><br /><sub><b>Cartelli Emmanuel</b></sub></a></td>
</tr>
</tbody>
</table>
<p align="center" style="line-height: 2.5;">
<a href="https://www.11ty.dev/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/35147177?v=4&s=100" height="80" style="vertical-align: middle;" alt="Eleventy" title="Eleventy"/></a>
<a href="https://www.opensense.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/opensense-inc/bf840ae/logo/256.png?height=100" height="80" style="vertical-align: middle;" alt="Opensense Inc." title="Opensense"/></a>
<a href="https://github.com/microsoft" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/6154722?v=4&s=100" height="80" style="vertical-align: middle;" alt="Microsoft" title="Microsoft"/></a>
<a href="https://sentry.io/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/1396951?v=4&s=100" height="80" style="vertical-align: middle;" alt="Sentry" title="Sentry"/></a>
<a href="https://github.com/Checkout-Blocks" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/114603307?v=4&s=100" height="80" style="vertical-align: middle;" alt="Checkout Blocks" title="Checkout Blocks"/></a>
<a href="https://customer.io/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/1152079?v=4&s=100" height="80" style="vertical-align: middle;" alt="Customer IO" title="Customer IO"/></a>
<a href="https://syntax.fm/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/130389858?v=4&s=100" height="80" style="vertical-align: middle;" alt="Syntax Podcast" title="Syntax Podcast"/></a>
<br/>
<a href="https://www.testmuai.com/?utm_medium=sponsor&utm_source=liquidjs" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/27130435?s=200&v=4" width="80" style="vertical-align: middle;" alt="TestMu AI" title="TestMu AI"/></a>
<a href="https://github.com/talboren" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/68807791?v=4&s=100" height="80" style="vertical-align: middle;" alt="Tal" title="Tal (@talboren)"/></a>
<a href="https://chudovo.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/Chudovo/avatar/256.png?height=100" width="160" style="vertical-align: middle;background: white;padding: 8px 16px;" alt="Chudovo" title="Chudovo"/></a>
<a href="https://dailycontributors.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/dailycontributors/3c2e057/logo/256.png?height=50&width=100" width="120" style="vertical-align: middle;" alt="Dailycontributors" title="Dailycontributors"/></a>
<a href="https://www.pakstyle.pk/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/pakstyle/2b81605/logo/256.png?height=100" height="80" style="vertical-align: middle;" alt="PakStyle.pk" title="PakStyle.pk"/></a>
<a href="https://www.escorta.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/escortacom/avatar/256.png?height=100" height="45" style="vertical-align: middle;" alt="EscortA.com" title="EscortA.com"/></a>
<br/>
<a href="https://opencollective.com/touchless" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/touchless/273bc74/logo/256.png?height=100" height="80" style="vertical-align: middle;" alt="Touchless" title="Touchless"/></a>
<a href="https://www.dropkiq.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/1bertlol/43a8ea8/logo/256.png?height=100" height="80" style="vertical-align: middle;" alt="Dropkiq" title="Dropkiq"/></a>
<a href="https://about.me/peterdehaan" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars2.githubusercontent.com/u/557895?v=4&s=100" height="80" style="vertical-align: middle;" alt="Peter deHaan" title="Peter deHaan"/></a>
<a href="https://github.com/coni2k" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars0.githubusercontent.com/u/1284601?v=4&s=100" height="80" style="vertical-align: middle;" alt="Serkan Holat" title="Serkan Holat"/></a>
<a href="https://github.com/amit777" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars0.githubusercontent.com/u/2703309?v=4&s=100" height="80" style="vertical-align: middle;" alt="amit777" title="amit777"/></a>
<a href="https://opencollective.com/khaled-salem" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/khaled-salem/avatar/256.png?height=256" height="80" style="vertical-align: middle;" alt="Khaled Salem" title="Khaled Salem"/></a>
<a href="https://github.com/15fathoms" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/79156039?v=4&s=100" height="80" style="vertical-align: middle;" alt="Emmanuel Cartelli" title="Emmanuel Cartelli"/></a>
<a href="https://opencollective.com/cartelli-emmanuel" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/cartelli-emmanuel/avatar/256.png?height=100" height="80" style="vertical-align: middle;" alt="Cartelli Emmanuel" title="Cartelli Emmanuel"/></a>
</p>
<!-- FINANCIAL-CONTRIBUTORS-END -->
## Contributors ✨
@@ -110,7 +124,7 @@ Want to contribute? see [Contribution Guidelines][contribution]. Thanks goes to
<table>
<tbody>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://harttle.land"><img src="https://avatars3.githubusercontent.com/u/4427974?v=4?s=100" width="100px;" alt="Jun Yang"/><br /><sub><b>Jun Yang</b></sub></a><br /><a href="#maintenance-harttle" title="Maintenance">🚧</a> <a href="https://github.com/harttle/liquidjs/commits?author=harttle" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/harttle"><img src="https://avatars3.githubusercontent.com/u/4427974?v=4?s=100" width="100px;" alt="Jun Yang"/><br /><sub><b>Jun Yang</b></sub></a><br /><a href="#maintenance-harttle" title="Maintenance">🚧</a> <a href="https://github.com/harttle/liquidjs/commits?author=harttle" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/chenos"><img src="https://avatars0.githubusercontent.com/u/2993310?v=4?s=100" width="100px;" alt="chenos"/><br /><sub><b>chenos</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=chenos" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://zachleat.com/"><img src="https://avatars2.githubusercontent.com/u/39355?v=4?s=100" width="100px;" alt="Zach Leatherman"/><br /><sub><b>Zach Leatherman</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/issues?q=author%3Azachleat" title="Bug reports">🐛</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/thardy"><img src="https://avatars3.githubusercontent.com/u/120636?v=4?s=100" width="100px;" alt="Tim Hardy"/><br /><sub><b>Tim Hardy</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=thardy" title="Code">💻</a></td>
@@ -210,6 +224,26 @@ Want to contribute? see [Contribution Guidelines][contribution]. Thanks goes to
</tr>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://tovd.dev"><img src="https://avatars.githubusercontent.com/u/35376389?v=4?s=100" width="100px;" alt="Tim van Dam"/><br /><sub><b>Tim van Dam</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=timvandam" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/edh649"><img src="https://avatars.githubusercontent.com/u/527604?v=4?s=100" width="100px;" alt="Ed Hanton"/><br /><sub><b>Ed Hanton</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=edh649" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://gurdiga.com"><img src="https://avatars.githubusercontent.com/u/53922?v=4?s=100" width="100px;" alt="Vlad GURDIGA"/><br /><sub><b>Vlad GURDIGA</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=gurdiga" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://www.streakingman.com"><img src="https://avatars.githubusercontent.com/u/30397306?v=4?s=100" width="100px;" alt="裸奔狂甩丁丁"/><br /><sub><b>裸奔狂甩丁丁</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=StreakingMan" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/skynetigor"><img src="https://avatars.githubusercontent.com/u/20903171?v=4?s=100" width="100px;" alt="Ihor Panasiuk"/><br /><sub><b>Ihor Panasiuk</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=skynetigor" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/rosomri"><img src="https://avatars.githubusercontent.com/u/68001413?v=4?s=100" width="100px;" alt="Omri Rosner"/><br /><sub><b>Omri Rosner</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=rosomri" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/immerrr"><img src="https://avatars.githubusercontent.com/u/579798?v=4?s=100" width="100px;" alt="immerrr again"/><br /><sub><b>immerrr again</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=immerrr" title="Documentation">📖</a></td>
</tr>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/rongjiecomputer"><img src="https://avatars.githubusercontent.com/u/13115060?v=4?s=100" width="100px;" alt="Loo Rong Jie"/><br /><sub><b>Loo Rong Jie</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=rongjiecomputer" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/MorielHarush"><img src="https://avatars.githubusercontent.com/u/93482738?v=4?s=100" width="100px;" alt="MorielHarush"/><br /><sub><b>MorielHarush</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=MorielHarush" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://doruk.ch"><img src="https://avatars.githubusercontent.com/u/77903714?v=4?s=100" width="100px;" alt="Peak Twilight"/><br /><sub><b>Peak Twilight</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=peaktwilight" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/joecottam"><img src="https://avatars.githubusercontent.com/u/44173086?v=4?s=100" width="100px;" alt="Joe Cottam"/><br /><sub><b>Joe Cottam</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=joecottam" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/timbze"><img src="https://avatars.githubusercontent.com/u/35117769?v=4?s=100" width="100px;" alt="Timmy Braun"/><br /><sub><b>Timmy Braun</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=timbze" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/talboren"><img src="https://avatars.githubusercontent.com/u/68807791?v=4?s=100" width="100px;" alt="Tal"/><br /><sub><b>Tal</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=talboren" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://filonov.dev"><img src="https://avatars.githubusercontent.com/u/813224?v=4?s=100" width="100px;" alt="Vladimir Filonov"/><br /><sub><b>Vladimir Filonov</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=VladimirFilonov" title="Code">💻</a></td>
</tr>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/spokodev"><img src="https://avatars.githubusercontent.com/u/239690017?v=4?s=100" width="100px;" alt="spokodev"/><br /><sub><b>spokodev</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=spokodev" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/YacovGold"><img src="https://avatars.githubusercontent.com/u/8984042?v=4?s=100" width="100px;" alt="YacovGold"/><br /><sub><b>YacovGold</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=YacovGold" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/sarathfrancis90"><img src="https://avatars.githubusercontent.com/u/9289498?v=4?s=100" width="100px;" alt="Sarath Francis"/><br /><sub><b>Sarath Francis</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=sarathfrancis90" title="Code">💻</a></td>
</tr>
</tbody>
</table>
@@ -219,8 +253,10 @@ Want to contribute? see [Contribution Guidelines][contribution]. Thanks goes to
<!-- ALL-CONTRIBUTORS-LIST:END -->
[shopify/liquid]: https://shopify.github.io/liquid/
[plugins]: https://liquidjs.com/tutorials/plugins.html#Plugin-List
## License
[MIT](LICENSE) © [Jun Yang](https://github.com/harttle)
[setup]: https://liquidjs.com/tutorials/setup.html
[doc]: https://liquidjs.com
[github]: https://github.com/harttle/liquidjs
+5 -3
View File
@@ -6,8 +6,10 @@ Only the latest major version is supported with security updates. It can be chan
## Reporting a Vulnerability
Please contact yangjvn@126.com to report a vulnerability or change request.
**Please do not report security vulnerabilities through public GitHub issues.**
- If the vulnerability in question affects common use cases, it will be treated as a bug and fixed very soon (typically within 1 week).
Report them via [GitHub Security Advisories — Report a vulnerability](https://github.com/harttle/liquidjs/security/advisories/new).
- If the vulnerability in question affects common use cases, it will be treated as a bug and fixed very soon (typically within a month).
- Otherwise, it'll be scheduled in the same priority of feature request (which is lower than bugs).
- If the request is declined, you'll receive a reply email anyway (most likely there will be a discussion).
- If the request is declined, you'll receive a reply anyway (most likely there will be a discussion).
-4
View File
@@ -1,4 +0,0 @@
#!/usr/bin/env bash
rm -rf docs/source/api
typedoc --plugin typedoc-plugin-missing-exports ./src --gitRevision master --out docs/source/api
+22
View File
@@ -0,0 +1,22 @@
const fs = require('fs')
const path = require('path')
const root = path.resolve(__dirname, '..')
const src = path.join(root, 'CHANGELOG.md')
let content = fs.readFileSync(src, 'utf8').replace(/\r\n/g, '\n')
const lines = content.split('\n')
lines[0] = lines[0]
.replace(/"/g, '&quot;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
content = lines.join('\n')
content = content
.replace(/{%/g, '{% raw %}{%{% endraw %}')
.replace(/\{\{/g, '{% raw %}{{{% endraw %}')
const enFrontmatter = '---\ntitle: Changelog\nauto: true\n---\n\n'
fs.writeFileSync(path.join(root, 'docs/source/tutorials/changelog.md'), enFrontmatter + content)
-15
View File
@@ -1,15 +0,0 @@
#!/usr/bin/env bash
cd docs
cp ../CHANGELOG.md source/tutorials/changelog.md
sed -i \
-e 's/{%/{% raw %}{%{% endraw %}/g' \
-e 's/{{/{% raw %}{{{% endraw %}/g' \
-e '1 s/"/\&quot;/g' \
-e '1 s/</\&lt;/g' \
-e '1 s/>/\&gt;/g' \
source/tutorials/changelog.md
cp source/tutorials/changelog.md source/zh-cn/tutorials/changelog.md
sed -i -e '1i\---\ntitle: Changelog\nauto: true\n---\n' source/tutorials/changelog.md
sed -i -e '1i\---\ntitle: 更新日志\nauto: true\n---\n' source/zh-cn/tutorials/changelog.md
+41
View File
@@ -0,0 +1,41 @@
const fs = require('fs')
const path = require('path')
const root = path.resolve(__dirname, '..')
const readme = fs.readFileSync(path.join(root, 'README.md'), 'utf8').replace(/\r\n/g, '\n')
function extractSection (text, beginMarker, endMarker) {
const lines = text.split('\n')
let inside = false
const result = []
for (const line of lines) {
if (line.includes(endMarker)) inside = false
if (inside) result.push(line)
if (line.includes(beginMarker)) inside = true
}
return result.join('\n')
}
function transformContributors (html) {
return html
.replace(/<br \/>.*?<\/td>/g, '</a></td>')
.replace(/width="[^"]*"/g, '')
.replace(/\n/g, '')
.replace(/<\/tr>\s*<tr>/g, '')
}
function transformFinancial (html) {
return html
.replace(/<br \/>.*?<\/td>/g, '</a></td>')
.replace(/\n/g, '')
.replace(/<\/tr>\s*<tr>/g, '')
}
const allContributors = transformContributors(extractSection(readme, 'ALL-CONTRIBUTORS-LIST:START', 'ALL-CONTRIBUTORS-LIST:END'))
const financialContributors = transformFinancial(extractSection(readme, 'FINANCIAL-CONTRIBUTORS-BEGIN', 'FINANCIAL-CONTRIBUTORS-END'))
const usedBy = transformFinancial(extractSection(readme, 'USED-BY-BEGIN', 'USED-BY-END'))
const outDir = path.join(root, 'docs/themes/navy/layout/partial')
fs.writeFileSync(path.join(outDir, 'all-contributors.swig'), allContributors)
fs.writeFileSync(path.join(outDir, 'financial-contributors.swig'), financialContributors)
fs.writeFileSync(path.join(outDir, 'used-by.swig'), usedBy)
-26
View File
@@ -1,26 +0,0 @@
#!/usr/bin/env bash
# Run `sed` in a way that's compatible with both macOS (BSD) and Linux (GNU)
sedi() {
if [[ "$OSTYPE" == "darwin"* ]]; then
/usr/bin/sed -i '' "$@"
else
sed -i "$@"
fi
}
# create docs/themes/navy/layout/partial/all-contributors.swig
awk '/ALL-CONTRIBUTORS-LIST:START/{flag=1;next}/ALL-CONTRIBUTORS-LIST:END/{flag=0}flag' README.md | \
sed 's/<br \/>.*<\/td>/<\/a><\/td>/g' | \
sed 's/width="[^"]*"//g' | \
tr -d '\n' | \
sed 's/<\/tr>\s*<tr>//g' \
> docs/themes/navy/layout/partial/all-contributors.swig
# create docs/themes/navy/layout/partial/financial-contributors.swig
awk '/FINANCIAL-CONTRIBUTORS-BEGIN/{flag=1;next}/FINANCIAL-CONTRIBUTORS-END/{flag=0}flag' README.md | \
sed 's/<br \/>.*<\/td>/<\/a><\/td>/g' | \
sed 's/width="[^"]*"//g' | \
tr -d '\n' | \
sed 's/<\/tr>\s*<tr>//g' \
> docs/themes/navy/layout/partial/financial-contributors.swig
-6
View File
@@ -1,6 +0,0 @@
#!/usr/bin/env bash
BUNDLES=min npm run build
mkdir -p docs/public/js/
cp dist/liquid.browser.min.js docs/public/js/
-17
View File
@@ -1,17 +0,0 @@
#!/usr/bin/env bash
set -ex
./bin/build-docs-liquid.sh
./bin/build-contributors.sh
./bin/build-apidoc.sh
./bin/build-changelog.sh
cd docs
npm ci
npm run build
cp CNAME public/
if [ "$HEXO_ALGOLIA_INDEXING_KEY" != "" ]; then
npm run index
fi
-36
View File
@@ -1,36 +0,0 @@
#!/usr/bin/env bash
# Prerequisites:
# 1.imagemagick. try brew install imagemagick
# 2. logo.png in size 512x512
# 3. this script should be run with cwd docs/source/icon/
echo creating apple touch icons...
apple=(57x57 60x60 72x72 76x76 114x114 120x120 144x144 152x152)
for size in "${apple[@]}"; do
echo $size
convert logo.png -resize $size apple-touch-icon-$size.png
done
cp logo.png apple-touch-icon.png
convert logo.png \
\( +clone -alpha extract \
-draw 'fill black polygon 0,0 0,80 80,0 fill white circle 80,80 80,0' \
\( +clone -flip \) -compose Multiply -composite \
\( +clone -flop \) -compose Multiply -composite \
\) -alpha off -compose CopyOpacity -composite apple-touch-icon-precomposed.png
echo creating favicon...
convert logo.png -resize 48x48 ../favicon.ico
favicon=(16x16 32x32 96x96 160x160 196x196)
for size in "${favicon[@]}"; do
echo $size
convert logo.png -resize $size favicon-$size.png
done
echo creating mstile icons...
mstile=(70x70 144x144 150x150 310x310)
for size in "${mstile[@]}"; do
echo $size
convert logo.png -resize $size mstile-$size.png
done
convert mstile-150x150.png -gravity center -background white -extent 310x150 mstile-310x150.png
+17
View File
@@ -0,0 +1,17 @@
const { execSync } = require('child_process')
const fs = require('fs')
const path = require('path')
const root = path.resolve(__dirname, '..')
const version = require(path.join(root, 'package.json')).version
const fileLocal = path.join(root, 'dist/liquid.node.js')
const fileLatest = path.join(root, `dist/liquid.node.${version}.js`)
if (!fs.existsSync(fileLatest)) {
const url = `https://unpkg.com/liquidjs@${version}/dist/liquid.node.js`
console.log(`Downloading liquidjs@${version}...`)
execSync(`curl -sL -o "${fileLatest}" "${url}"`)
}
execSync(`node benchmark/diff.js "${fileLocal}" "${fileLatest}"`, { cwd: root, stdio: 'inherit' })
-12
View File
@@ -1,12 +0,0 @@
#!/usr/bin/env bash
VERSION_LATEST=$(cat package.json | grep '"version":' | head -1 | awk -F'"' '{print $4}')
FILE_LOCAL=dist/liquid.node.js
FILE_LATEST=dist/liquid.node.$VERSION_LATEST.js
URL_LATEST=https://unpkg.com/liquidjs@$VERSION_LATEST/dist/liquid.node.js
if [ ! -f "$FILE_LATEST" ]; then
curl $URL_LATEST > $FILE_LATEST
fi
exec node benchmark/diff.js $FILE_LOCAL $FILE_LATEST
+1 -1
View File
@@ -8,7 +8,7 @@
"test": "echo not implemented",
"start": "http-server -c-1 "
},
"author": "harttle <yangjvn@126.com>",
"author": "harttle <harttleharttle@gmail.com>",
"license": "ISC",
"dependencies": {
"http-server": "^0.11.1",
+1 -1
View File
@@ -8,7 +8,7 @@ const engine = new Liquid({
// layout files for `{% layout %}`
layouts: process.cwd() + '/layouts',
// partial files for `{% include %}` and `{% render %}`
partials: process.cwd() + '/partials'
partials: [process.cwd() + '/partials', 'node_modules']
})
const ctx = {
+1 -1
View File
@@ -1,3 +1,3 @@
set -ex
set -e
npm start | grep 'LiquidJS Demo'
+1 -1
View File
@@ -1,4 +1,4 @@
set -x
set -e
LOG_FILE=$(mktemp)
npm start > $LOG_FILE 2>&1 &
+1 -1
View File
@@ -1,3 +1,3 @@
set -ex
set -e
npm start | grep 'NodeJS Demo for LiquidJS'
+1 -1
View File
@@ -1,3 +1,3 @@
set -ex
set -e
npm start | grep '\[11:8] {{ todo }}'
+1 -1
View File
@@ -1,3 +1,3 @@
set -ex
set -e
npm run build && npm start | grep 'TypeScript Demo for LiquidJS'
+1 -1
View File
@@ -1,4 +1,4 @@
set -ex
set -e
npm run build
npm start | grep 'Webpack Demo for LiquidJS'
+5 -7
View File
@@ -1,10 +1,8 @@
title: LiquidJS
subtitle: "A simple, expressive and safe template engine."
description: "LiquidJS is a simple, expressive and safe Shopify / GitHub Pages compatible template engine in pure JavaScript."
subtitle: "A simple, expressive, extensible Liquid template engine for JavaScript"
description: "A simple, expressive, extensible Liquid template engine for JavaScript — Shopify, Jekyll and GitHub Pages compatible, for Node.js, browsers, and the CLI, with TypeScript support."
author: Harttle
language:
- en
- zh-cn
language: en
timezone: UTC
url: https://liquidjs.com
@@ -30,8 +28,8 @@ prismjs:
tab_replace: ""
algolia:
applicationID: 0X19J927JZ
apiKey: 533161d821384919672e4ce8a39451b3
applicationID: QJ35YOZTU4
apiKey: 8c6cbb824b4c5023f0bb2ef29e228bef
indexName: liquidjs
twitter: harttleharttle
github: harttle/liquidjs
+2
View File
@@ -2,6 +2,8 @@
'use strict'
require('./prism-bash-extend')
const { resolve, basename } = require('path')
const { readFileSync } = require('fs')
const cheerio = require('cheerio')
+34
View File
@@ -0,0 +1,34 @@
'use strict'
/**
* Extend Prism's bash grammar with extra CLI commands for docs code blocks.
* Hexo loads scripts from docs/scripts/ during init, before `hexo generate`
* highlights fenced code via syntax_highlighter: prismjs.
*
* Bash highlights known commands via a large hard-coded regex (see prism-bash).
* insertBefore is the supported extension point when a command is not in that list.
* Add names to EXTRA_BASH_COMMANDS as needed.
*
* After editing this file, run `npx hexo clean` before generate/serve so
* Hexo re-highlights cached pages (db.json does not invalidate on script changes).
*/
const EXTRA_BASH_COMMANDS = [
'npx'
]
const Prism = require('prismjs')
require('prismjs/components/prism-bash')
const escaped = EXTRA_BASH_COMMANDS.map((cmd) =>
cmd.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
)
Prism.languages.insertBefore('bash', 'function', {
'cli-command': {
pattern: new RegExp(
`(^|[\\s;|&]|[<>]\\()(?:${escaped.join('|')})(?=$|[)\\s;|&])`
),
lookbehind: true,
alias: ['builtin', 'class-name']
}
})
-2
View File
@@ -1,3 +1 @@
en: English
zh-cn:
name: 简体中文
-24
View File
@@ -1,24 +0,0 @@
-
url: https://opencollective.com/liquidjs/#section-contribute
date: '2020-02-26'
title:
zh-cn: '赞助人:第一个 backer 通过 Open Collective 贡献于 LiquidJS。'
en: 'Backers: the first backer contributed to LiquidJS via Open Collective.'
-
url: https://github.com/harttle/liquidjs/pull/202
date: '2020-03-11'
title:
zh-cn: '内存优化:用更精细的手法重写了解析器,来避免临时字符串的生成,内存占用降低 57.7% 以上。'
en: 'Memory Optimization: a more elaborate parser reducing the memory footprint by 57.7%.'
-
url: https://github.com/harttle/liquidjs/pull/205
date: '2020-03-15'
title:
zh-cn: '性能提升:引入 AST 并重新设计 Token 类型系统,使渲染性能平均提升 100.3%。'
en: 'Performance Boost: a simple AST to improve render performance by 100.3%.'
-
url: https://github.com/harttle/liquidjs/milestone/3?closed=1
date: '2021-09-30'
title:
zh-cn: '流式渲染:4 倍渲染速度,并增加了对流式渲染的支持。'
en: 'Streamed Rendering: now render is 4x faster and support streamed rendering.'
+10 -2
View File
@@ -19,7 +19,8 @@ tutorials:
plugins: plugins.html
operators: operators.html
truth: truthy-and-falsy.html
dos: dos.html
security_model: security-model.html
static_analysis: static-analysis.html
miscellaneous:
migration9: migrate-to-9.html
changelog: changelog.html
@@ -50,10 +51,14 @@ filters:
escape_once: escape_once.html
find: find.html
find_exp: find_exp.html
find_index: find_index.html
find_index_exp: find_index_exp.html
first: first.html
floor: floor.html
group_by: group_by.html
group_by_exp: group_by_exp.html
has: has.html
has_exp: has_exp.html
inspect: inspect.html
join: join.html
json: json.html
@@ -71,6 +76,8 @@ filters:
push: push.html
prepend: prepend.html
raw: raw.html
reject: reject.html
reject_exp: reject_exp.html
remove: remove.html
remove_first: remove_first.html
remove_last: remove_last.html
@@ -87,6 +94,7 @@ filters:
sort: sort.html
sort_natural: sort_natural.html
split: split.html
squish: squish.html
strip: strip.html
strip_html: strip_html.html
strip_newlines: strip_newlines.html
@@ -107,7 +115,7 @@ filters:
tags:
overview: overview.html
"#": inline_comment.html
"# (inline comment)": inline_comment.html
assign: assign.html
capture: capture.html
case: case.html
+27
View File
@@ -0,0 +1,27 @@
---
title: base64_decode
---
{% since %}v10.24.0{% endsince %}
Decodes a Base64-formatted string back to its original text.
Input
```liquid
{{ "b25lIHR3byB0aHJlZQ==" | base64_decode }}
```
Output
```text
one two three
```
Input
```liquid
{{ "SGVsbG8sIFdvcmxkISBAIyQl" | base64_decode }}
```
Output
```text
Hello, World! @#$%
```
+27
View File
@@ -0,0 +1,27 @@
---
title: base64_encode
---
{% since %}v10.24.0{% endsince %}
Encodes a string into Base64 format.
Input
```liquid
{{ "one two three" | base64_encode }}
```
Output
```text
b25lIHR3byB0aHJlZQ==
```
Input
```liquid
{{ "Hello, World! @#$%" | base64_encode }}
```
Output
```text
SGVsbG8sIFdvcmxkISBAIyQl
```
+7 -6
View File
@@ -3,18 +3,18 @@ title: date
---
{% since %}v1.9.1{% endsince %}
Date filter is used to convert a timestamp into the specified format.
The `date` filter is used to convert a timestamp into the specified format.
* LiquidJS tries to conform to Shopify/Liquid, which uses Ruby's core [Time#strftime(string)](https://www.ruby-doc.org/core/Time.html#method-i-strftime). There're differences with [Ruby's format flags](https://ruby-doc.org/core/strftime_formatting_rdoc.html):
* LiquidJS tries to conform to Shopify/Liquid, which uses Ruby's core [Time#strftime(string)](https://www.ruby-doc.org/core/Time.html#method-i-strftime). There are differences with [Ruby's format flags](https://ruby-doc.org/core/strftime_formatting_rdoc.html):
* `%Z` (since v10.11.1) is replaced by the passed-in timezone name from `LiquidOption` or in-place value (see TimeZone below). If passed-in timezone is an offset number instead of string, it'll behave like `%z`. If there's none passed-in timezone, it returns [the runtime's default time zone](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/resolvedOptions#timezone).
* LiquidJS provides an additional `%q` flag for date ordinals. e.g. `{{ '2023/02/02' | date: '%d%q of %b'}}` => `02nd of Feb`
* Date literals are firstly converted to `Date` object via [new Date()][jsDate], that means literal values are considered in runtime's time zone by default.
* Date literals are first converted to a `Date` object via [new Date()][jsDate], which means literal values are considered in the runtime's time zone by default.
* The format filter argument is optional:
* If not provided, it defaults to `%A, %B %-e, %Y at %-l:%M %P %z`.
* The above default can be overridden by [`dateFormat`](/api/interfaces/LiquidOptions.html#dateFormat) LiquidJS option.
* LiquidJS `date` supports locale specific weekdays and month names, which will fallback to English where `Intl` is not supported.
* Ordinals (`%q`) and Jekyll specific date filters are English-only.
* [`locale`](/api/interfaces/LiquidOptions.html#locale) can be set when creating Liquid instance. Defaults to `Intl.DateTimeFormat().resolvedOptions.locale`).
* [`locale`](/api/interfaces/LiquidOptions.html#locale) can be set when creating a Liquid instance. Defaults to `Intl.DateTimeFormat().resolvedOptions().locale`.
### Examples
```liquid
@@ -26,14 +26,15 @@ Date filter is used to convert a timestamp into the specified format.
```
# TimeZone
* During output, LiquidJS uses local timezone which can override by:
* During output, LiquidJS uses the local timezone, which can be overridden by:
* setting a timezone in-place when calling `date` filter, or
* setting the [`timezoneOffset`](/api/interfaces/LiquidOptions.html#timezoneOffset) LiquidJS option
* It defaults to runtime's time one.
* It defaults to the runtime's timezone.
* Offset can be set as,
* minutes: `-360` means `'+06:00'` and `360` means `'-06:00'`
* timeZone ID: `Asia/Colombo` or `America/New_York`
* See [here](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) for TZ database values
* `%s` (seconds since the Unix epoch) identifies an instant rather than a wall-clock time, so it's not affected by the display timezone.
### Examples
```liquid
+25
View File
@@ -0,0 +1,25 @@
---
title: find_index
---
{% since %}v10.21.0{% endsince %}
Return the 0-based index of the first object in an array for which the queried attribute has the given value or return `nil` if no item in the array satisfies the given criteria. For the following `members` array:
```javascript
const members = [
{ graduation_year: 2013, name: 'Jay' },
{ graduation_year: 2014, name: 'John' },
{ graduation_year: 2014, name: 'Jack' }
]
```
Input
```liquid
{{ members | find_index: "graduation_year", 2014 | json }}
```
Output
```text
1
```
+25
View File
@@ -0,0 +1,25 @@
---
title: find_index_exp
---
{% since %}v10.21.0{% endsince %}
Return the 0-based index of the first object in an array for which the given expression evaluates to true or return `nil` if no item in the array satisfies the evaluated expression.
```javascript
const members = [
{ graduation_year: 2013, name: 'Jay' },
{ graduation_year: 2014, name: 'John' },
{ graduation_year: 2014, name: 'Jack' }
]
```
Input
```liquid
{{ members | find_index_exp: "item", "item.graduation_year == 2014" | json }}
```
Output
```text
1
```
+25
View File
@@ -0,0 +1,25 @@
---
title: has
---
{% since %}v10.21.0{% endsince %}
Return `true` if the array includes an item for which the queried attribute has the given value or return `false` if no item in the array satisfies the given criteria. For the following `members` array:
```javascript
const members = [
{ graduation_year: 2013, name: 'Jay' },
{ graduation_year: 2014, name: 'John' },
{ graduation_year: 2014, name: 'Jack' }
]
```
Input
```liquid
{{ members | has: "graduation_year", 2014 | json }}
```
Output
```text
true
```
+25
View File
@@ -0,0 +1,25 @@
---
title: has_exp
---
{% since %}v10.21.0{% endsince %}
Return `true` if an item exists in an array for which the given expression evaluates to true or return `false` if no item in the array satisfies the evaluated expression.
```javascript
const members = [
{ graduation_year: 2013, name: 'Jay' },
{ graduation_year: 2014, name: 'John' },
{ graduation_year: 2014, name: 'Jack' }
]
```
Input
```liquid
{{ members | has_exp: "item", "item.graduation_year == 2014" | json }}
```
Output
```text
true
```
+20
View File
@@ -0,0 +1,20 @@
---
title: hmac_sha256
---
{% since %}vNEXT{% endsince %}
Converts a string into an SHA-256 hash using a hash message authentication code (HMAC). The secret key is passed as the filter argument. The output is a lowercase hexadecimal string.
Input
```liquid
{%- assign secret_potion = 'Polyjuice' | hmac_sha256: 'Polina' -%}
My secret potion: {{ secret_potion }}
```
Output
```text
My secret potion: 8e0d5d65cff1242a4af66c8f4a32854fd5fb80edcc8aabe9b302b29c7c71dc20
```
+1 -1
View File
@@ -4,7 +4,7 @@ title: json
{% since %}v9.10.0{% endsince %}
Convert values to string via `JSON.stringify()`, for debug purpose.
Convert values to string via `JSON.stringify()`, for debugging purposes.
Input
```liquid
+9 -7
View File
@@ -5,15 +5,17 @@ description: Description and demo for each Liquid filter
LiquidJS implements business-logic independent filters that are typically implemented in [shopify/liquid][shopify/liquid]. This section contains the specification and demos for all the filters implemented by LiquidJS.
There's 40+ filters supported by LiquidJS. These filters can be categorized into these groups:
There are 40+ filters supported by LiquidJS. These filters can be categorized into these groups:
Categories | Filters
--- | ---
Math | plus, minus, modulo, times, floor, ceil, round, divided_by, abs, at_least, at_most
String | append, prepend, capitalize, upcase, downcase, strip, lstrip, rstrip, strip_newlines, split, replace, replace_first, replace_last,remove, remove_first, remove_last, truncate, truncatewords, normalize_whitespace, number_of_words, array_to_sentence_string
HTML/URI | escape, escape_once, url_encode, url_decode, strip_html, newline_to_br, xml_escape, cgi_escape, uri_escape, slugify
Array | slice, map, sort, sort_natural, uniq, where, where_exp, group_by, group_by_exp, find, find_exp, first, last, join, reverse, concat, compact, size, push, pop, shift, unshift
Date | date, date_to_xmlschema, date_to_rfc822, date_to_string, date_to_long_string
Misc | default, json, jsonify, inspect, raw, to_integer
Math | `plus`, `minus`, `modulo`, `times`, `floor`, `ceil`, `round`, `divided_by`, `abs`, `at_least`, `at_most`
String | `append`, `prepend`, `capitalize`, `upcase`, `downcase`, `strip`, `lstrip`, `rstrip`, `strip_newlines`, `split`, `replace`, `replace_first`, `replace_last`,`remove`, `remove_first`, `remove_last`, `truncate`, `truncatewords`, `normalize_whitespace`, `number_of_words`, `array_to_sentence_string`
HTML/URI | `escape`, `escape_once`, `url_encode`, `url_decode`, `strip_html`, `newline_to_br`, `xml_escape`, `cgi_escape`, `uri_escape`, `slugify`
Array | `slice`, `map`, `sort`, `sort_natural`, `uniq`, `where`, `where_exp`, `group_by`, `group_by_exp`, `find`, `find_exp`, `first`, `last`, `join`, `reverse`, `concat`, `compact`, `size`, `push`, `pop`, `shift`, `unshift`
Date | `date`, `date_to_xmlschema`, `date_to_rfc822`, `date_to_string`, `date_to_long_string`
Misc | `default`, `json`, `jsonify`, `inspect`, `raw`, `to_integer`
Base64 | `base64_encode`, `base64_decode`
Crypto | `sha256`, `hmac_sha256`
[shopify/liquid]: https://github.com/Shopify/liquid
+118
View File
@@ -0,0 +1,118 @@
---
title: reject
---
{% since %}v10.21.0{% endsince %}
Creates an array excluding the objects with a given property value, or excluding [truthy][truthy] values by default when a property is not given.
In this example, assume you have a list of products and you want to filter out kitchen products. Using `reject`, you can create an array excluding only the products that have a `"type"` of `"kitchen"`.
Input
```liquid
All products:
{% for product in products %}
- {{ product.title }}
{% endfor %}
{% assign non_kitchen_products = products | reject: "type", "kitchen" %}
Kitchen products:
{% for product in non_kitchen_products %}
- {{ product.title }}
{% endfor %}
```
Output
```text
All products:
- Vacuum
- Spatula
- Television
- Garlic press
Kitchen products:
- Vacuum
- Television
```
Say instead you have a list of products and you want to exclude taxable products. You can `reject` with a property name but no target value to reject all products with a [truthy][truthy] `"taxable"` value.
Input
```liquid
All products:
{% for product in products %}
- {{ product.title }}
{% endfor %}
{% assign not_taxed_products = products | reject: "taxable" %}
Available products:
{% for product in not_taxed_products %}
- {{ product.title }}
{% endfor %}
```
Output
```text
All products:
- Vacuum
- Spatula
- Television
- Garlic press
Available products:
- Spatula
- Television
```
Additionally, `property` can be any valid Liquid variable expression as used in output syntax, except that the scope of this expression is within each item. For the following `products` array:
```javascript
const products = [
{ meta: { details: { class: 'A' } }, order: 1 },
{ meta: { details: { class: 'B' } }, order: 2 },
{ meta: { details: { class: 'B' } }, order: 3 }
]
```
Input
```liquid
{% assign selected = products | reject: 'meta.details["class"]', "B" %}
{% for item in selected -%}
- {{ item.order }}
{% endfor %}
```
Output
```text
- 1
```
## Jekyll style
{% since %}v10.21.0{% endsince %}
For Liquid users migrating from Jekyll, there's a `jekyllWhere` option to mimic the behavior of Jekyll's `where` filter. This option is set to `false` by default. When enabled, if `property` is an array, the target value is matched using `Array.includes` instead of `==`, which is particularly useful for excluding tags.
```javascript
const pages = [
{ tags: ["cat", "food"], title: 'Cat Food' },
{ tags: ["dog", "food"], title: 'Dog Food' },
]
```
Input
```liquid
{% assign selected = pages | reject: 'tags', "cat" %}
{% for item in selected -%}
- {{ item.title }}
{% endfor %}
```
Output
```text
Dog Food
```
[truthy]: ../tutorials/truthy-and-falsy.html
+37
View File
@@ -0,0 +1,37 @@
---
title: reject_exp
---
{% since %}v10.21.0{% endsince %}
Select all the objects in an array where the expression is false. In this example, assume you have a list of products and you want to hide your kitchen products. Using `reject_exp`, you can create an array that omits only the products that have a `"type"` of `"kitchen"`.
Input
```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 %}
```
Output
```text
All products:
- Vacuum
- Spatula
- Television
- Garlic press
Kitchen products:
- Vacuum
- Television
```
[truthy]: ../tutorials/truthy-and-falsy.html
+20
View File
@@ -0,0 +1,20 @@
---
title: sha256
---
{% since %}vNEXT{% endsince %}
Converts a string into an SHA-256 hash. The output is a lowercase hexadecimal string.
Input
```liquid
{%- assign secret_potion = 'Polyjuice' | sha256 -%}
My secret potion: {{ secret_potion }}
```
Output
```text
My secret potion: 44ac1d7a2936e30a5de07082fd65d6fe9b1fb658a1a98bfe65bc5959beac5dd0
```
+18
View File
@@ -0,0 +1,18 @@
---
title: squish
---
{% since %}v10.28.0{% endsince %}
Removes leading and trailing whitespace from a string, and replaces every run of whitespace inside it with a single space.
Input
```liquid
{{ " Hello there,
Major Tom. " | squish }}
```
Output
```text
Hello there, Major Tom.
```
+8
View File
@@ -6,6 +6,10 @@ title: strip_html
Removes any HTML tags from a string.
{% note warn Not safe for HTML output %}
This filter removes tags by string scanning; it does not parse HTML5 the way a browser does, and it is not a sanitizer. The result may still be unsafe when inserted into HTML. Use [escape][escape], [escape_once][escape_once], or [`outputEscape: "escape"`][outputEscape] for untrusted output.
{% endnote %}
Input
```liquid
{{ "Have <em>you</em> read <strong>Ulysses</strong>?" | strip_html }}
@@ -15,3 +19,7 @@ Output
```text
Have you read Ulysses?
```
[escape]: ./escape.html
[escape_once]: ./escape.html
[outputEscape]: ../tutorials/options.html#outputEscape
+1 -1
View File
@@ -36,7 +36,7 @@ Ground control, and so on
## No ellipsis
You can truncate to the exact number of characters specified by the first argument and avoid showing trailing characters by passing a blank string as the second argument:
You can `truncate` to the exact number of characters specified by the first argument and avoid showing trailing characters by passing a blank string as the second argument:
Input
```liquid
+5 -3
View File
@@ -37,6 +37,7 @@ Kitchen products:
```
Say instead you have a list of products and you only want to show those that are available to buy. You can `where` with a property name but no target value to include all products with a [truthy][truthy] `"available"` value.
As a special case, the same will happen if the target value is given but evaluates to `undefined`.
Input
```liquid
@@ -70,7 +71,6 @@ The `where` filter can also be used to find a single object in an array when com
Input
```liquid
{% assign new_shirt = products | where: "type", "shirt" | first %}
Featured product: {{ new_shirt.title }}
```
@@ -105,9 +105,11 @@ Output
## Jekyll style
{% since %}v10.19.0{% endsince %}
{% since %}v10.21.0{% endsince %}
For Liquid users migrating from Jekyll, there's a `jekyllWhere` option to mimic the behavior of Jekyll's `where` filter. This option is set to `false` by default. When enabled, if `property` is an array, the target value is matched using `Array.includes` instead of `==`, which is particularly useful for filtering tags.
For Liquid users migrating from Jekyll, there's a `jekyllWhere` option to mimic the behavior of Jekyll's `where` filter. This option is set to `false` by default. When enabled, if `property` is an array, the target value is matched using `Array.includes` instead of `==`, which is particularly useful for filtering tags. Additionally, a target value of `undefined` is treated normally, entries matched are exactly those which are themselves `undefined`.
This option affects other array selection filters as well, such as `reject` and `find`.
```javascript
const pages = [
+8 -10
View File
@@ -1,29 +1,27 @@
layout: index
description: LiquidJS is a simple, expressive and safe Shopify / GitHub Pages compatible template engine in pure JavaScript.
subtitle: A simple, expressive and safe template engine.
---
ul#intro-feature-list
li.intro-feature-wrap
.intro-feature
.intro-feature-icon
i.icon-shield
h3.intro-feature-title Safe Rendering
p.intro-feature-desc Liquid templates are highly readable and fault-tolerant thus suitable for designers and customers. Operators and expressions are parsed to AST and no #[code eval] or #[code new Function] are used.
h3.intro-feature-title Safe &amp; Typed
p.intro-feature-desc Templates are readable and fault-tolerant, parsed to an AST with no #[code eval] or #[code new Function]. The whole repo is written in TypeScript strict mode, so types stay precise and docs accurate.
li.intro-feature-wrap
.intro-feature
.intro-feature-icon
i.icon-rocket
h3.intro-feature-title Pure JavaScript
p.intro-feature-desc Written with pure JavaScript with no native bindings, available in both Node.js and browsers. All of the CMD, ESM and CJS bundles are available on CDN.
p.intro-feature-desc Written in pure JavaScript with no native bindings, running in both Node.js and the browser. The CMD, ESM and CJS bundles are all available on CDN.
li.intro-feature-wrap
.intro-feature
.intro-feature-icon
i.icon-shopify
h3.intro-feature-title Shopify Compatible
p.intro-feature-desc All filters and tags from Ruby #[a(href="https://github.com/shopify/liquid") shopify/liquid] are supported by LiquidJS. #[a(href="https://jekyllrb.com/") Jekyll sites], #[a(href="https://pages.github.com/") GitHub Pages] and #[a(href="https://themes.shopify.com/") Shopify templates] can be ported to Node.js without pain.
h3.intro-feature-title Shopify &amp; Jekyll
p.intro-feature-desc All filters and tags from Ruby #[a(href="https://github.com/shopify/liquid") shopify/liquid] are supported, so #[a(href="https://themes.shopify.com/") Shopify templates] work out of the box — as do #[a(href="https://jekyllrb.com/") Jekyll] sites and #[a(href="https://pages.github.com/") GitHub Pages].
li.intro-feature-wrap
.intro-feature
.intro-feature-icon
i.icon-typescript
h3.intro-feature-title TypeScript Strict
p.intro-feature-desc The whole repo is re-written in TypeScript strict mode to ensure a smooth experience using this lib and the document is precise and always up to date.
i.icon-network
h3.intro-feature-title Streaming
p.intro-feature-desc Render directly to a Node.js stream with #[code renderToNodeStream], emitting output as it's produced — for a faster time to first byte and low memory usage on large pages.
+28
View File
@@ -0,0 +1,28 @@
# LiquidJS
> A simple, expressive, extensible Liquid template engine for JavaScript
## Tutorials
- [Introduction to Liquid](https://liquidjs.com/tutorials/intro-to-liquid.html)
- [Setup](https://liquidjs.com/tutorials/setup.html)
- [Options](https://liquidjs.com/tutorials/options.html)
- [Render files](https://liquidjs.com/tutorials/render-file.html)
- [Partials and layouts](https://liquidjs.com/tutorials/partials-and-layouts.html)
- [Express.js](https://liquidjs.com/tutorials/use-in-expressjs.html)
- [Register filters and tags](https://liquidjs.com/tutorials/register-filters-tags.html)
- [Plugins](https://liquidjs.com/tutorials/plugins.html)
- [Sync and async](https://liquidjs.com/tutorials/sync-and-async.html)
- [Operators](https://liquidjs.com/tutorials/operators.html)
- [Truthy and falsy](https://liquidjs.com/tutorials/truthy-and-falsy.html)
- [Security model](https://liquidjs.com/tutorials/security-model.html)
- [Differences from Shopify Liquid](https://liquidjs.com/tutorials/differences.html)
- [Migrate to v9](https://liquidjs.com/tutorials/migrate-to-9.html)
- [Changelog](https://liquidjs.com/tutorials/changelog.html)
## Reference
- [Tags](https://liquidjs.com/tags/overview.html)
- [Filters](https://liquidjs.com/filters/overview.html)
- [API (TypeDoc)](https://liquidjs.com/api/)
- [Playground](https://liquidjs.com/playground.html)
+1 -1
View File
@@ -1,7 +1,7 @@
{
"short_name": "LiquidJS",
"name": "LiquidJS",
"description": "A simple, expressive and safe Shopify / GitHub Pages compatible template engine in pure JavaScript.",
"description": "A simple, expressive, extensible Liquid template engine for JavaScript",
"icons": [
{
"src": "/icon/apple-touch-icon-57x57.png",
Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

+1
View File
@@ -10,6 +10,7 @@ const urlsToCache = [
]
const blackList = [
/chrome-extension:/,
/algolia.net/,
/google-analytics.com.*collect/
]
+1 -1
View File
@@ -1,5 +1,5 @@
---
title: Assign
title: assign
---
{% since %}v1.9.1{% endsince %}
+1 -1
View File
@@ -4,7 +4,7 @@ title: case
{% since %}v1.9.1{% endsince %}
Creates a switch statement to compare a variable with different values. `case` initializes the switch statement, and `when` compares its values.
Creates a switch statement to compare a variable with different values. `case` initializes the switch statement, and `when` tags compare values.
Input
```liquid
+1 -1
View File
@@ -1,5 +1,5 @@
---
title: Comment
title: comment
---
{% since %}v1.9.1{% endsince %}
+1 -1
View File
@@ -1,5 +1,5 @@
---
title: Decrement
title: decrement
---
{% since %}v1.9.1{% endsince %}
+2 -2
View File
@@ -1,10 +1,10 @@
---
title: Echo
title: echo
---
{% since %}v9.31.0{% endsince %}
Outputs an expression in the rendered HTML. This is identical to wrapping an expression in `{{` and `}}`, but works inside liquid tags and supports filters.
Outputs an expression in the rendered HTML. This is identical to wrapping an expression in <code>{{</code> and <code>}}</code>, but works inside liquid tags and supports filters.
## echo
+1 -1
View File
@@ -1,5 +1,5 @@
---
title: For
title: for
---
{% since %}v1.9.1{% endsince %}
+1 -1
View File
@@ -1,5 +1,5 @@
---
title: If
title: if
---
{% since %}v1.9.1{% endsince %}
+7 -7
View File
@@ -1,5 +1,5 @@
---
title: Include
title: include
---
{% since %}v1.9.1{% endsince %}
@@ -22,11 +22,11 @@ If [extname][extname] option is set, the above `.liquid` extension becomes optio
{% include 'footer' %}
```
When a partial template is rendered by `include`, the code inside it can access its parent's variables but its parent cannot access variables defined inside a included template.
When a partial template is rendered by `include`, the code inside it can access its parent's variables but its parent cannot access variables defined inside an included template.
## Passing Variables
Variables defined in parent's scope can be passed to a the partial template by listing them as parameters on the `include` tag:
Variables defined in the parent's scope can be passed to the partial template by listing them as parameters on the `include` tag:
```liquid
{% assign my_variable = 'apples' %}
@@ -70,11 +70,11 @@ This way, you don't need to escape `"` in the filename expression.
{% include prefix/{{name | append: ".html"}} %}
```
## Jekyll include
## Jekyll `include`
{% since %}v9.33.0{% endsince %}
[jekyllInclude][jekyllInclude] is used to enable Jekyll-like include syntax. Defaults to `false`, when set to `true`:
[jekyllInclude][jekyllInclude] is used to enable Jekyll-like `include` syntax. Defaults to `false`, when set to `true`:
- Filename will be static: `dynamicPartials` now defaults to `false` (instead of `true`). And you can set `dynamicPartials` back to `true`.
- Use `=` instead of `:` to separate parameter key-values.
@@ -86,7 +86,7 @@ For example, the following template:
{% include article.html header="HEADER" content="CONTENT" %}
```
`article.html` with following content:
`article.html` with the following content:
```liquid
<article>
@@ -95,7 +95,7 @@ For example, the following template:
</article>
```
Note that we're referencing the first parameter by `include.header` instead of `header`. Will output following:
Note that we're referencing the first parameter by `include.header` instead of `header`. It will output the following:
```html
<article>
+1 -1
View File
@@ -1,5 +1,5 @@
---
title: Increment
title: increment
---
{% since %}v1.9.1{% endsince %}
+5 -5
View File
@@ -1,5 +1,5 @@
---
title: Layout
title: layout
---
{% since %}v1.9.1{% endsince %}
@@ -31,12 +31,12 @@ If [extname][extname] option is set, the `.liquid` extension becomes optional:
```
{% note info Scoping %}
When a partial template is rendered by <code>layout</code>, its template have access for its caller's variables but not vice versa. Variables defined in layout will be popped out before control returning to its caller.
When a partial template is rendered by the `layout` tag, its template has access to its caller's variables but not vice versa. Variables defined in `layout` will be popped out before control returns to its caller.
{% endnote %}
## Multiple Blocks
The layout file can contain multiple blocks, each with a specified name. The following snippets yield same result as in the above example.
The `layout` file can contain multiple blocks, each with a specified name. The following snippets yield same result as in the above example.
```liquid
// default-layout.liquid
@@ -53,7 +53,7 @@ The layout file can contain multiple blocks, each with a specified name. The fol
## Default Block Contents
In the above layout files, blocks has empty contents. But it's not necessarily be empty, in which case, the block contents in layout files will be used as default templates. The following snippets are also equivalent to the above examples:
In the above `layout` files, blocks have empty contents. They do not necessarily need to be empty; in that case, the block contents in `layout` files will be used as default templates. The following snippets are also equivalent to the above examples:
```liquid
// default-layout.liquid
@@ -68,7 +68,7 @@ In the above layout files, blocks has empty contents. But it's not necessarily b
## Passing Variables
Variables defined in current template can be passed to a the layout template by listing them as parameters on the `layout` tag:
Variables defined in the current template can be passed to the `layout` template by listing them as parameters on the `layout` tag:
```liquid
{% assign my_variable = 'apples' %}
+1 -1
View File
@@ -1,5 +1,5 @@
---
title: Liquid
title: liquid
---
{% since %}v9.31.0{% endsince %}
+6 -6
View File
@@ -5,14 +5,14 @@ description: Description and demo for each Liquid tag
LiquidJS implements business-logic independent tags that are typically implemented in [shopify/liquid][shopify/liquid]. This section contains the specification and demos for all the tags implemented by LiquidJS.
There're a dozen of tags supported by LiquidJS, with all tags in [shopify/liquid][shopify/liquid]. These tags can be categorized into these groups:
There are a dozen tags supported by LiquidJS, including all tags in [shopify/liquid][shopify/liquid]. These tags can be categorized into these groups:
Category | Purpose | Tags
--- | --- | ---
Iteration | iterate over a collection | for, cycle, tablerow
Control Flow | control the execution branch of template rendering | if, unless, elsif, else, case, when
Variable | define and alter variables | assign, increment, decrement, capture, echo
File | include another template or extend a layout template | render, include, layout
Language | temporarily disable LiquidJS syntax | # (inline comment), raw, comment, liquid
Iteration | iterate over a collection | `for`, `cycle`, `tablerow`
Control Flow | control the execution branch of template rendering | `if`, `unless`, `elsif`, `else`, `case`, `when`
Variable | define and alter variables | `assign`, `increment`, `decrement`, `capture`, `echo`
File | include another template or extend a layout template | `render`, `include`, `layout`
Language | temporarily disable LiquidJS syntax | `#`, `raw`, `comment`, `liquid`
[shopify/liquid]: https://github.com/Shopify/liquid
+1 -1
View File
@@ -1,5 +1,5 @@
---
title: Raw
title: raw
---
{% since %}v1.9.1{% endsince %}
+2 -2
View File
@@ -1,5 +1,5 @@
---
title: Render
title: render
---
{% since %}v9.2.0{% endsince %}
@@ -32,7 +32,7 @@ When a partial template is rendered, the code inside it can't access its parent'
## Passing Variables
Variables defined in parent's scope can be passed to a the partial template by listing them as parameters on the render tag:
Variables defined in the parent's scope can be passed to the partial template by listing them as parameters on the `render` tag:
```liquid
{% assign my_variable = 'apples' %}
+3 -3
View File
@@ -1,5 +1,5 @@
---
title: Table Row
title: tablerow
---
{% since %}v1.9.1{% endsince %}
@@ -88,7 +88,7 @@ Output
### limit
Exits the tablerow after a specific index.
Exits the `tablerow` after a specific index.
```liquid
{% tablerow product in collection.products cols:2 limit:3 %}
@@ -98,7 +98,7 @@ Exits the tablerow after a specific index.
### offset
Starts the tablerow after a specific index.
Starts the `tablerow` after a specific index.
```liquid
{% tablerow product in collection.products cols:2 offset:3 %}
+1 -1
View File
@@ -1,5 +1,5 @@
---
title: Unless
title: unless
---
{% since %}v1.9.1{% endsince %}
@@ -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 -2
View File
@@ -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,15 @@ 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]. If I'm missing anything, find me via Twitter (harttleharttle) or email (harttleharttle at gmail), to add you into [the contributors table](https://github.com/harttle/liquidjs#contributors-).
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.
If I'm missing anything or you observed it not working, please don't hesitate to file an issue or find me via email (harttleharttle at gmail).
[oc]: https://opencollective.com/liquidjs/contribute/backer-10665/checkout
[shopify/liquid]: https://shopify.github.io/liquid/
+5 -3
View File
@@ -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.
@@ -24,6 +24,7 @@ Though we're trying to be compatible with the Ruby version, there are still some
* Truthy and Falsy. All values except `undefined`, `null`, `false` are truthy, whereas in Ruby Liquid all except `nil` and `false` are truthy. See [#26][#26].
* Number. In JavaScript we cannot distinguish or convert between `float` and `integer`, see [#59][#59]. And when applied `size` filter, numbers always return 0, which is 8 for integer in ruby, cause they do not have a `length` property.
* Stringify: We've aligned string coercion for primitive types. While some differences remain; for example, in Shopify/liquid, `strip` returns the "inspected" string of an input array, whereas in LiquidJS, the `strip` filter simply stringifies the input array [#852][#852].
* [.to_liquid()](https://github.com/Shopify/liquid/wiki/Introduction-to-Drops) is replaced by `.toLiquid()`
* [.to_s()](https://www.rubydoc.info/gems/liquid/Liquid/Drop) is replaced by JavaScript `.toString()`
* Iteration order for objects. The iteration order of JavaScript objects, and thus LiquidJS objects, is a combination of the insertion order for string keys, and ascending order for number-like keys, while the iteration order of Ruby Hash is simply the insertion order.
@@ -47,6 +48,7 @@ Though we're trying to be compatible with the Ruby version, there are still some
[#236]: https://github.com/harttle/liquidjs/issues/236
[#414]: https://github.com/harttle/liquidjs/discussions/414
[#485]: https://github.com/harttle/liquidjs/discussions/485
[#852]: https://github.com/harttle/liquidjs/discussions/852
[sort]: https://liquidjs.com/filters/sort.html
[stable-sort]: https://v8.dev/features/stable-sort
[plugins]: ./plugins.html#Plugin-List
-57
View File
@@ -1,57 +0,0 @@
---
title: DoS Prevention
---
When the template or data context cannot be trusted, enabling DoS prevention options is crucial. LiquidJS provides 3 options for this purpose: `parseLimit`, `renderLimit`, and `memoryLimit`.
## TL;DR
Setting these options can largely ensure that your LiquidJS instance won't hang for extended periods or consume excessive memory. These limits are based on the available JavaScript APIs, so they are not precise hard limits but thresholds to help prevent your process from failing or hanging.
```typescript
const liquid = new Liquid({
parseLimit: 1e8, // typical size of your templates in each render
renderLimit: 1000, // limit each render to be completed in 1s
memoryLimit: 1e9, // memory available for LiquidJS (1e9 for 1GB)
})
```
When a `parse()` or `render()` cannot be completed within given resource, it throws.
## parseLimit
[parseLimit][parseLimit] restricts the size (character length) of templates parsed in each `.parse()` call, including referenced partials and layouts. Since LiquidJS parses template strings in near O(n) time, limiting total template length is usually sufficient.
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.
```liquid
{%- for i in (1..10000000) -%}
order: {{i}}
{%- endfor -%}
```
Render time is checked on a per-template basis (before rendering each template). In the above example, there are 2 templates in the loop: `order: ` and `{{i}}`, render time will be checked 10000000x2 times.
For time-consuming tags and filters within a single template, the process can still hang. For fully controlled rendering, consider using a process manager like [paralleljs][paralleljs].
## memoryLimit
Even with 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: "," %}
{% for i in (1..32) %}
{% assign array = array | concat: array %}
{% endfor %}
```
[memoryLimit][memoryLimit] restricts memory-sensitive filters to prevent excessive memory allocation. As [JavaScript uses GC to manage memory](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_management), `memoryLimit` limits only the total number of objects allocated by memory sensitive filters in LiquidJS thus may not reflect the actual memory footprint.
[paralleljs]: https://www.npmjs.com/package/paralleljs
[parseLimit]: /api/interfaces/LiquidOptions.html#parseLimit
[renderLimit]: /api/interfaces/LiquidOptions.html#renderLimit
[memoryLimit]: /api/interfaces/LiquidOptions.html#memoryLimit
+1 -1
View File
@@ -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'
+3 -3
View File
@@ -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
+4 -5
View File
@@ -3,9 +3,9 @@ title: The Liquid Template Language
describe: A short introduction to the Liquid template language and some simple demos.
---
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].
Liquid is a template language originally implemented in Ruby and used by Shopify, Jekyll, and GitHub Pages. LiquidJS implements it in JavaScript; see [Differences with Shopify/liquid][diff] for compatibility notes.
LiquidJS syntax is relatively simple. There're 2 types of markups in LiquidJS:
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,11 +50,10 @@ 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 %}
```
A complete list of tags supported by LiquidJS can be found [here](../tags/overview.html).
[shopify/liquid]: https://github.com/Shopify/liquid
[diff]: ./differences.html
+3 -3
View File
@@ -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).
+54 -7
View File
@@ -2,20 +2,67 @@
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: `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.
## Logical Operators
### not
Negates a condition. Returns `true` if the condition is false, and `false` if the condition is true.
Input
```liquid
{% if not user.active %}
User is inactive
{% endif %}
```
### and
Returns `true` if both conditions are true.
Input
```liquid
{% if user.age >= 18 and user.verified %}
Access granted
{% endif %}
```
### or
Returns `true` if at least one condition is true.
Input
```liquid
{% if user.isAdmin or user.isModerator %}
You have elevated privileges
{% endif %}
```
### contains
Checks if a string contains a substring, or if an array contains an element.
Input
```liquid
{% if product.title contains "Pack" %}
This is a pack
{% endif %}
```
## Precedence
1. Comparison operators. All comparison operations have the same precedence and higher than logic operators.
2. Logic operators. All logic operators have the same precedence.
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 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://help.shopify.com/en/themes/liquid/basics/operators#order-of-operations
[operator-order]: https://shopify.dev/docs/api/liquid/basics#order-of-operations
+16 -16
View File
@@ -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,15 +108,15 @@ 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.
**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.
## Trimming
@@ -146,7 +146,7 @@ Nonexistent tags always throw errors during parsing and this behavior cannot be
## Parameter Order
Parameter orders are ignored by default, for ea `{% for i in (1..8) reversed limit:3 %}` will always perform `limit` before `reversed`, even if `reversed` occurs before `limit`. To make parameter order respected, set **orderedFilterParameters** to `true`. Its default value is `false`.
Parameter orders are ignored by default, for example `{% for i in (1..8) reversed limit:3 %}` will always perform `limit` before `reversed`, even if `reversed` occurs before `limit`. To make parameter order respected, set **orderedFilterParameters** to `true`. Its default value is `false`.
[liquid]: /api/classes/Liquid.html
[caching]: ./caching.html
+2 -2
View File
@@ -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 &quot;.liquid&quot; 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.
+2 -2
View File
@@ -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
/**
+21 -3
View File
@@ -10,7 +10,7 @@ import { Value, TagToken, Context, Emitter, TopLevelToken } from 'liquidjs'
engine.registerTag('upper', {
parse: function(tagToken: TagToken, remainTokens: TopLevelToken[]) {
this.value = new Value(token.args, liquid)
this.value = new Value(tagToken.args, engine)
},
render: function*(ctx: Context) {
const str = yield this.value.value(ctx); // 'alice'
@@ -62,7 +62,23 @@ 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.
Filters can be unregistered by name:
```javascript
engine.unregisterFilter('plus')
```
With [`strictFilters`][strict-filters] enabled, using an unregistered filter will throw an error. Otherwise, the filter will be skipped.
Built-in filters can be registered again using the exported `filters` object:
```javascript
import { filters } from 'liquidjs'
engine.registerFilter('plus', filters.plus)
```
To disable a tag, or to make a disabled filter throw regardless of `strictFilters`, register a dummy implementation that throws a corresponding error (see [#324](https://github.com/harttle/liquidjs/issues/324)):
```javascript
// disable a tag
@@ -80,4 +96,6 @@ function disabledFilter(name) {
}
}
engine.registerFilter('plus', disabledFilter('plus'));
```
```
[strict-filters]: /tutorials/options.html#strict
+10 -16
View File
@@ -38,33 +38,27 @@ 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.
```javascript
var engine = new Liquid({
root: ['views/', 'views/partials/'],
root: ['views/'],
partials: ['views/partials/'],
layouts: ['views/layouts/'],
extname: '.liquid'
});
```
{% note tip Relative Paths %}Relative paths in <code>root</code> will be resolved against <code>cwd()</code>.{% endnote %}
When `{% raw %}{% render "foo" %}{% endraw %}` is rendered or `liquid.renderFile('foo')` is called, the following files will be looked up and the first existing file will be used:
- When `parse()`, `render()` functions are called, for example `liquid.renderFile('foo')`, templates under `root` will be looked up.
- When a partial is requested, for example `{% raw %}{% render "foo" %}{% endraw %}`, templates under `partials` will be looked up.
- When a layout is requested, for example `{% raw %}{% layout "foo" %}{% endraw %}`, templates under `layouts` will be looked up.
- `cwd()`/views/foo.liquid
- `cwd()`/views/partials/foo.liquid
If none of the above files exists, an `ENOENT` error will be thrown. Here's a demo for Node.js: [demo/nodejs](https://github.com/harttle/liquidjs/tree/master/demo/nodejs).
When LiquidJS is used in browser, say current location is <https://example.com/bar/index.html>, only the first `root` will be used and the file to be fetched is:
- <https://example.com/bar/foo.liquid>
If fetch fails, a 404/500 error or network failures for example, an `ENOENT` error will be thrown.
Here's a demo for browsers: [demo/browser](https://github.com/harttle/liquidjs/tree/master/demo/browser).
When LiquidJS is used in browser, the paths will be resolved based on current location. Here's a demo for browsers: [demo/browser](https://github.com/harttle/liquidjs/tree/master/demo/browser).
## Abstract File System
@@ -98,11 +92,11 @@ var engine = new Liquid({
});
```
{% note warn Path Traversal Vulnerability %}The default value of <code>contains()</code> always returns true. That means when specifying an abstract file system, you'll need to provide a proper <code>contains()</code> to avoid expose such vulnerabilities.{% endnote %}
{% note warn Path Traversal Vulnerability %}The built-in Node <code>fs</code> implements <code>contains()</code> with realpath so templates cannot escape the root via symlinks. The browser bundle omits <code>contains</code> (loader treats paths as allowed). For a custom abstract <code>fs</code>, implement <code>contains</code> unless every resolved path is trusted.{% endnote %}
## 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({
+6 -6
View File
@@ -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 %}
+89
View File
@@ -0,0 +1,89 @@
---
title: Security Model
---
LiquidJS provides DoS-oriented limits (`parseLimit`, `renderLimit`, `memoryLimit`) to reduce risk. This page summarizes those limits, [`ownPropertyOnly`][ownPropertyOnly], custom [`Drop`][drop] usage, and the security boundary to assume in production.
## Security boundary
The built-in limits are cooperative safeguards, not strict runtime isolation.
- They do **not** equal process RSS/heap usage.
- They do **not** sandbox JavaScript execution.
- They should be combined with process/container limits and request timeouts for defense in depth.
## Limits at a glance
- [parseLimit][parseLimit]: limit total template size per `parse()` call.
- [renderLimit][renderLimit]: limit total render time per `render()` call.
- [memoryLimit][memoryLimit]: cooperatively limit memory-sensitive allocations counted by LiquidJS.
## Limit details
### parseLimit
[parseLimit][parseLimit] restricts the size (character length) of templates parsed in each `.parse()` call, including referenced partials and layouts. Since LiquidJS parses template strings in near O(n) time, limiting total template length is usually sufficient.
A typical PC handles `1e8` (100M) characters without issues.
### renderLimit
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) -%}
order: {{i}}
{%- endfor -%}
```
Render time is checked on a per-template basis (before rendering each template). In the above example, there are 2 templates in the loop: `order: ` and `{{i}}`, render time will be checked 10000000x2 times.
`renderLimit` is not a hard CPU limiter. It is checked between template renders, so compute-intensive filters/tags/user-defined functions or deeply nested template execution between checks can still cause DoS.
### memoryLimit
`memoryLimit` only limits operations that LiquidJS explicitly counts.
- Counted: memory-sensitive LiquidJS operations that call internal memory accounting.
- Not guaranteed counted: arbitrary user object behavior such as custom `toValue()`/`toString()` chains, or other host-side code that allocates outside LiquidJS accounting points.
In other words, `memoryLimit` limits what LiquidJS counts, not every byte your process may allocate.
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: "," %}
{% for i in (1..32) %}
{% assign array = array | concat: array %}
{% endfor %}
```
As [JavaScript uses GC to manage memory](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_management), `memoryLimit` may not reflect the actual memory footprint.
## `ownPropertyOnly` and scope data
With [`ownPropertyOnly`][ownPropertyOnly] `true`, plain scope objects only expose **own** properties (no inherited / `Object.prototype` keys). Default `false` follows normal JS property access. Use `true` for untrusted or polluted objects; add [`strictVariables`][strictVariables] if missing paths should error. Override per render via [`RenderOptions`][renderOwnPropertyOnly]. This is a read policy for scope data—not a sandbox for filters, tags, or your code.
## Custom `Drop` classes
[`Drop`][drop] values are not restricted the same way: LiquidJS still reads the prototype chain and may call [`liquidMethodMissing`][liquidMethodMissing]. **You** control what a drop exposes; narrow APIs and never feed unsafe data into drops unless the class is built for template access. `ownPropertyOnly` alone does not harden custom drops—audit them like any privileged code.
## Online service guidance
If you run an online service, avoid rendering fully user-defined templates whenever possible.
- Prefer curated templates or a restricted template subset.
- If user-defined templates are required, isolate rendering (worker/process/container), enforce OS/container memory and CPU limits, and apply request rate limits.
- Treat `parseLimit`/`renderLimit`/`memoryLimit` as one layer in a broader DoS defense strategy.
For heavy single-template operations, process-level isolation is still recommended (for example with [paralleljs][paralleljs]).
[paralleljs]: https://www.npmjs.com/package/paralleljs
[parseLimit]: /api/interfaces/LiquidOptions.html#parseLimit
[renderLimit]: /api/interfaces/LiquidOptions.html#renderLimit
[memoryLimit]: /api/interfaces/LiquidOptions.html#memoryLimit
[ownPropertyOnly]: /api/interfaces/LiquidOptions.html#ownPropertyOnly
[renderOwnPropertyOnly]: /api/interfaces/RenderOptions.html#ownPropertyOnly
[strictVariables]: /api/interfaces/LiquidOptions.html#strictVariables
[drop]: /api/classes/Drop.html
[liquidMethodMissing]: /api/classes/Drop.html#liquidMethodMissing
+1 -1
View File
@@ -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 %}
+290
View File
@@ -0,0 +1,290 @@
---
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. Internal structures returned can be changed without a major version bump.
{% endnote %}
{% note info Sync and Async %}
There are synchronous and asynchronous versions of each of the methods demonstrated on this page. See the [Liquid API][liquid-api] for a complete reference.
{% endnote %}
## Variables
Retrieve the names of variables used in a template with `Liquid.variables(template)`. It returns an array of strings, one string for each distinct variable, without its properties.
```javascript
import { Liquid } from 'liquidjs'
const engine = new Liquid()
const template = engine.parse(`
<p>
{% 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 }}
<p>
`)
console.log(engine.variablesSync(template))
```
**Output**
```javascript
[ 'user', 'title', 'email', 'a', 'b' ]
```
Notice that variables from tag and filter arguments are included, as well as nested variables like `b` in the example. Alternatively, use `Liquid.fullVariables(template)` to get a list of variables including their properties as strings.
```javascript
// continued from above
engine.fullVariables(template).then(console.log)
```
**Output**
```javascript
[
'user.title',
'user.first_name',
'user.name',
'user.last_name',
'user.address',
'user.address.line1',
'user.email_addresses[0]',
'user.email_addresses',
'title',
'email',
'a[b.c].d',
'b.c'
]
```
Or use `Liquid.variableSegments(template)` to get an array of strings and numbers that make up each variable's path.
```javascript
// continued from above
engine.variableSegments(template).then(console.log)
```
**Output**
```javascript
[
[ 'user', 'title' ],
[ 'user', 'first_name' ],
[ 'user', 'name' ],
[ 'user', 'last_name' ],
[ 'user', 'address' ],
[ 'user', 'address', 'line1' ],
[ 'user', 'email_addresses', 0 ],
[ 'user', 'email_addresses' ],
[ 'title' ],
[ 'email' ],
[ 'a', [ 'b', 'c' ], 'd' ],
[ 'b', 'c' ]
]
```
### Global Variables
Notice, in the examples above, that `title` and `email` are included in the results. Often you'll want to exclude names that are in scope from `{% assign %}` tags, and temporary variables like those introduced by a `{% for %}` tag.
To get names that are expected to be _global_, that is, provided by application developers rather than template authors, use the `globalVariables`, `globalFullVariables` or `globalVariableSegments` methods (or their synchronous equivalents) of a `Liquid` class instance.
```javascript
// continued from above
engine.globalVariableSegments(template).then(console.log)
```
**Output**
```javascript
[
[ 'user', 'title' ],
[ 'user', 'first_name' ],
[ 'user', 'name' ],
[ 'user', 'last_name' ],
[ 'user', 'address' ],
[ 'user', 'address', 'line1' ],
[ 'user', 'email_addresses', 0 ],
[ 'user', 'email_addresses' ],
[ 'a', [ 'b', 'c' ], 'd' ],
[ 'b', 'c' ]
]
```
### Partial Templates
By default, LiquidJS will try to load and analyze any included and rendered templates too.
```javascript
import { Liquid } from 'liquidjs'
const footer = `
<footer>
<p>&copy; {{ "now" | date: "%Y" }} {{ site_name }}</p>
<p>{{ site_description }}</p>
</footer>`
const engine = new Liquid({ templates: { footer } })
const template = engine.parse(`
<body>
<h1>Hi, {{ you | default: 'World' }}!</h1>
{% assign some = 'thing' %}
{% include 'footer' %}
</body>
`)
engine.globalVariables(template).then(console.log)
```
**Output**
```javascript
[ 'you', 'site_name', 'site_description' ]
```
You can disable analysis of partial templates by setting the `partials` options to `false`.
```javascript
// continue from above
engine.globalVariables(template, { partials: false }).then(console.log)
```
**Output**
```javascript
[ 'you' ]
```
If an `{% include %}` tag uses a dynamic template name (one that can't be determined without rendering the template) it will be ignored, even if `partials` is set to `true`.
### Advanced Usage
The examples so far all use convenience methods of the `Liquid` class, intended to cover the most common use cases. Instead, you can work with [analysis results][static-analysis-interface] directly, which expose the row, column and file name for every occurrence of each variable.
This is an example of an object returned from `Liquid.analyze()`, passing it the template from the [Partial Template](#partial-templates) section above.
```javascript
{
variables: {
you: [
[String (Variable): 'you'] {
segments: [ 'you' ],
location: { row: 2, col: 14, file: undefined }
}
],
site_name: [
[String (Variable): 'site_name'] {
segments: [ 'site_name' ],
location: { row: 2, col: 41, file: 'footer' }
}
],
site_description: [
[String (Variable): 'site_description'] {
segments: [ 'site_description' ],
location: { row: 3, col: 9, file: 'footer' }
}
]
},
globals: {
you: [
[String (Variable): 'you'] {
segments: [ 'you' ],
location: { row: 2, col: 14, file: undefined }
}
],
site_name: [
[String (Variable): 'site_name'] {
segments: [ 'site_name' ],
location: { row: 2, col: 41, file: 'footer' }
}
],
site_description: [
[String (Variable): 'site_description'] {
segments: [ 'site_description' ],
location: { row: 3, col: 9, file: 'footer' }
}
]
},
locals: {
some: [
[String (Variable): 'some'] {
segments: [ 'some' ],
location: { row: 3, col: 13, file: undefined }
}
]
}
}
```
### 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.
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.
Whether a tag is an inline tag or a block tag, if it accepts arguments it should implement [`arguments()`](/api/interfaces/Template.html#arguments), which is responsible for returning the tag's arguments as a sequence of [`Value`](/api/classes/Value.html) instances or tokens of type [`ValueToken`](/api/types/ValueToken.html).
This example demonstrates these methods for a block tag. See LiquidJS's [built-in tags][built-in] for more examples.
```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)
}
}
```
[liquid-api]: /api/classes/Liquid.html
[static-analysis-interface]: /api/interfaces/StaticAnalysis.html
[built-in]: https://github.com/harttle/liquidjs/tree/master/src/tags
+5 -5
View File
@@ -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 -2
View File
@@ -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 -2
View File
@@ -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');
+2 -2
View File
@@ -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" -%}
-39
View File
@@ -1,39 +0,0 @@
---
title: abs
---
{% since %}v1.9.1{% endsince %}
返回数字的绝对值。
输入
```liquid
{{ -17 | abs }}
```
输出
```text
17
```
输入
```liquid
{{ 4 | abs }}
```
输出
```text
4
```
对于只包含数字的字符串也好使:
输入
```liquid
{{ "-19.86" | abs }}
```
输出
```text
19.86
```

Some files were not shown because too many files have changed in this diff Show More