GithubHelp home page GithubHelp logo

azu / liquidjs Goto Github PK

View Code? Open in Web Editor NEW

This project forked from harttle/liquidjs

0.0 2.0 0.0 2.92 MB

A shopify compatible Liquid template engine in pure JavaScript.

Home Page: https://jsfiddle.net/6u40xbzs/

License: MIT License

TypeScript 99.84% Liquid 0.03% HTML 0.02% JavaScript 0.11%

liquidjs's Introduction

liquidjs

npm npm Build Status Coveralls GitHub issues GitHub contributors David David Dev DUB Commitizen friendly semantic-release

A shopify compatible Liquid template engine in pure JavaScript. Install via npm:

npm install --save liquidjs

Or include the UMD build (You may need a Promise polyfill for Node.js < 4 and ES5 browsers like IE and Android UC):

<script src="//unpkg.com/liquidjs/dist/liquid.min.js"></script>     <!--for production-->
<script src="//unpkg.com/liquidjs/dist/liquid.js"></script>         <!--for development-->

The purpose of this repo is to provide a standard Liquid implementation for the JavaScript community. All features, filters and tags in shopify/liquid are supposed to be supported here, though there are still some differences:

  • Dynamic file locating (enabled by default), that means layout/partial names are treated as variables in liquidjs. See #51.
  • Truthy and Falsy. All values except undefined, null, false are truthy, whereas in Ruby Liquid all except nil and false are truthy. See #26.
  • Number. In JavaScript we cannot distinguish or convert between float and integer, see #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.
  • .to_liquid() is replaced by .toLiquid()
  • .to_s() is replaced by JavaScript .toString()

Features that available on shopify website but not on shopify/liquid repo will not be implemented in this repo, but there're some plugins available (feel free to add yours):

TOC

Render from String

Just render a template string with a context:

var Liquid = require('liquidjs');
var engine = new Liquid();

engine
    .parseAndRender('{{name | capitalize}}', {name: 'alice'})
    .then(console.log);     // outputs 'Alice'

Caching parsed templates:

var tpl = engine.parse('{{name | capitalize}}');
engine
    .render(tpl, {name: 'alice'})
    .then(console.log);     // outputs 'Alice'

Render from File

var engine = new Liquid({
    root: path.resolve(__dirname, 'views/'),  // root for layouts/includes lookup
    extname: '.liquid'          // used for layouts/includes, defaults ""
});
engine
    .renderFile("hello", {name: 'alice'})   // will read and render `views/hello.liquid`
    .then(console.log)  // outputs "Alice"

Or from the CLI:

echo '{{ "hello" | capitalize }}' | liquidjs

Use with Express.js

// register liquid engine
app.engine('liquid', engine.express()); 
app.set('views', './views');            // specify the views directory
app.set('view engine', 'liquid');       // set to default

views in express.js will be included when looking up partials(includes and layouts).

Include Partials

// file: color.liquid
color: '{{ color }}' shape: '{{ shape }}'

// file: theme.liquid
{% assign shape = 'circle' %}
{% include 'color' %}
{% include 'color' with 'red' %}
{% include 'color', color: 'yellow', shape: 'square' %}

The output will be:

color: '' shape: 'circle'
color: 'red' shape: 'circle'
color: 'yellow' shape: 'square'

Layout Templates (Extends)

// file: default-layout.liquid
Header
{% block content %}My default content{% endblock %}
Footer

// file: page.liquid
{% layout "default-layout" %}
{% block content %}My page content{% endblock %}

The output of page.liquid:

Header
My page content
Footer
  • It's possible to define multiple blocks.
  • block name is optional when there's only one block.

Options

The full list of options for Liquid() is listed as following:

  • root is a directory or an array of directories to resolve layouts and includes, as well as the filename passed in when calling .renderFile(). If an array, the files are looked up in the order they occur in the array. Defaults to ["."]

  • extname is used to lookup the template file when filepath doesn't include an extension name. Eg: setting to ".html" will allow including file by basename. Defaults to "".

  • cache indicates whether or not to cache resolved templates. Defaults to false.

  • dynamicPartials: if set, treat <filepath> parameter in {%include filepath %}, {%layout filepath%} as a variable, otherwise as a literal value. Defaults to true.

  • strictFilters is used to enable strict filter existence. If set to false, undefined filters will be rendered as empty string. Otherwise, undefined filters will cause an exception. Defaults to false.

  • strictVariables is used to enable strict variable derivation. If set to false, undefined variables will be rendered as empty string. Otherwise, undefined variables will cause an exception. Defaults to false.

  • trimTagRight is used to strip blank characters (including , \t, and \r) from the right of tags ({% %}) until \n (inclusive). Defaults to false.

  • trimTagLeft is similiar to trimTagRight, whereas the \n is exclusive. Defaults to false. See Whitespace Control for details.

  • trimOutputRight is used to strip blank characters (including , \t, and \r) from the right of values ({{ }}) until \n (inclusive). Defaults to false.

  • trimOutputLeft is similiar to trimOutputRight, whereas the \n is exclusive. Defaults to false. See Whitespace Control for details.

  • tagDelimiterLeft and tagDelimiterRight are used to override the delimiter for liquid tags.

  • outputDelimiterLeft and outputDelimiterRight are used to override the delimiter for liquid outputs.

  • greedy is used to specify whether trim*Left/trim*Right is greedy. When set to true, all consecutive blank characters including \n will be trimed regardless of line breaks. Defaults to true.

  • fs is used to override the default file-system module with a custom implementation.

Register Filters

// Usage: {{ name | uppper }}
engine.registerFilter('upper', v => v.toUpperCase())

Filter arguments will be passed to the registered filter function, for example:

// Usage: {{ 1 | add: 2, 3 }}
engine.registerFilter('add', (initial, arg1, arg2) => initial + arg1 + arg2)

See existing filter implementations here: https://github.com/harttle/liquidjs/tree/master/src/builtin/filters

Register Tags

// Usage: {% upper name%}
engine.registerTag('upper', {
    parse: function(tagToken, remainTokens) {
        this.str = tagToken.args; // name
    },
    render: async function(scope, hash) {
        var str = await Liquid.evalValue(this.str, scope); // 'alice'
        return str.toUpperCase()  // 'Alice'
    }
});
  • parse: Read tokens from remainTokens until your end token.
  • render: Combine scope data with your parsed tokens into HTML string.

See existing tag implementations here: https://github.com/harttle/liquidjs/tree/master/src/builtin/tags

Plugin API

A pack of tags or filters can be encapsulated into a plugin, which will be typically installed via npm.

engine.plugin(require('./some-plugin'));

// some-plugin.js
module.exports = function (Liquid) {
    // here `this` refers to the engine instance
    // `Liquid` provides facilities to implement tags and filters
    this.registerFilter('foo', x => x);
}

Contribute Guidelines

This repo uses eslint to check code style, semantic-release to generate changelog and publish to npm and Github Releases.

liquidjs's People

Contributors

aleclarson avatar chenos avatar cmawhorter avatar harttle avatar jaswrks avatar oott123 avatar paulrobertlloyd avatar pmalouin avatar robinbijlani avatar ryaninvents avatar scottfreecode avatar semantic-release-bot avatar ssendev avatar stevenanthonyrevo avatar strax avatar thardy avatar thehappybug avatar thelornenelson avatar wojtask9 avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.