npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@mywheels/viscousjs

v1.5.1

Published

A simple templating language similar to Liquid

Downloads

102

Readme

npm version types included minified size

Viscous.js is a simple and straightforward templating engine, similar to Liquid(.js), but with some modifications so that it's nicer to use:

  • Operator precedence is taken into account.
  • Nested parenthesized expressions are allowed.
  • Helper function calls can be used.
  • Less strict on certain control flow block names: {% else if %} and {% elseif %} are acceptable variations of {% elsif %}, and {% end %} can be used instead of {% endXYZ %}.

It doesn't yet have feature parity, because these things (amongst others) are still missing:

  • Helper loop variables like forloop and index0 etc.
  • Other kinds of iteration
  • The comment, cycle, increment, decrement, raw, and capture tags
  • Async data / rendering

And then there are certain features that I'm probably won'y be adding (unless someone wishes to contribute):

  • The include, case/when, layout, render, and tablerow tags

Usage

import { parseAndEvaluate, parseAndRender } from "@mywheels/viscousjs";

const data = {
  happy: true,
  hello: {
    world: 40,
  },
};

// 42
const result = parseAndEvaluate(`hello.world + 2`, data);

// "clap your hands"
const output = parseAndRender(`
  {%- if happy -%}
    clap your hands
  {%- end -%}
`);

Overview

Control flow

  • if
    • {% if <cond> %}
    • {% elsif <cond> %}
      • or {% elseif <cond> %}
      • or {% else if <cond> %}
    • {% else %}
    • {% endif %}
      • or just {% end %}
  • unless
    • {% unless <cond> %}
    • {% endunless %}
      • or just {% end %}
  • for
    • {% for <name> in <arr> %}
      • or {% for <name> of <arr> %}
    • {% endfor %}
      • or just {% end %}
  • assignment
    • {% assign <name> = <expression> %}

Interpolation

  • {{ <expression> }}
  • {{ <expression> | <filter> }}
  • {{ <expression> | <filter>: <args> }}
  • {{ <expression> | ... | ... | ... }}

Whitespace control

Both interpolation and control flow blocks accept whitespace trimmers at either end, for example {% if true -%} or {{- expr -}}. These trim whitespace off of the preceding and/or succeeding raw template pieces.

Expressions

You can form expressions with all the ordinary mathematical operators and comparators, double and triple (in)equality, and contains (which works for strings as well as arrays).

Also, you can use helper functions in expressions like max(a, b) or cond(d, a, b).

Filters

Interpolation blocks accept filters, which transform the evaluated expression before interpolating it into the output.

  • {{ name | upper }} might become "ROSE"
  • {{ 8 | max: 4 }} becomes "4"

You can use multiple filters:

  • {{ 3.14 | min: 0 | ceil }} becomes "4"

You can pass multiple arguments:

  • {{ 8 | clamp: 4, 6 }} becomes "6"

You can use expressions in filters:

  • {{ fuelLevel | clamp: config.minLevel, config.maxLevel }}

Providing your own helpers and filters

Filters are just helpers which are passed the interpolated value as first argument. For example, {{ 8 | max: 4 }} evaluates as max(8, 4).

You can register additional helper functions in the helpers config key:

parseAndRender(`
    {{ hello | world }}
    {{ dino | raise: food, love }}
  `,
  data,
  {
    helpers: {
      world(hello) { ... },
      raise(dino, food, love) { ... },
    },
  }
);

Truthiness

Like Liquid, an expression is considered truthy whenever it's a true, a number, a string or an object. So, also "" and 0 and [] are considered truthy.

You can also provide your own truthiness check with the isTruthy config key.

Failure

If the template fails to parse or render, parseAndEvaluate will return undefined, and parseAndRender will return an empty string. If you want parse or runtime errors to be thrown instead, you pass the config key throwOnError: true.

Configuration

type ViscousConfig = {
  helpers?: Record<string, Function>;
  isTruthy?: (data: any) => boolean;
  throwOnError?: boolean;
  evaluate?: (expr: ExprNode, env?: any) => any;
};

Known helpers and filters

More will be added soon. (And just make a PR if you want to contribute yours :))

  • general purpose

    • default (fallback)
    • stringify (data)
  • numeric

    • abs (num)
    • ceil (num)
    • floor (num)
    • at_least (min)
    • at_most (max)
    • clamp (min, max)
  • strings

    • append (str)
    • upcase (str)
      • upper (str)
    • downcase (str)
      • lower (str)
  • control

    • if (cond, a, b)
      • cond (cond, a, b)

Alternatives

  • Liquid.js — the origin of Viscous.js
  • Handlebars — all-time simplicity's favorite
  • Twig.js — quite similar to Liquid.js; a port of PHP's twig engine
  • EJS — "JavaScript but then in a templating language", way more powerful but not ideal as a content format
  • ...and more...