Giter Club home page Giter Club logo

mutton's Introduction

mutton

A simple and very lightweight mustache-like template compiler and renderer. The values of template variables are computed using a function that is provided by the user. Additionally, if the template contains exactly one variable and nothing else, the original type of the computed value is preserved. See the usage section below for examples.

Installation

npm install mutton --save

Usage

Rendering

Simple templated rendered:

import { renderTemplate } from 'mutton';

const data = {
  name: 'Austin',
  age: 9001,
};

const rendered = renderTemplate(
  'My name is {{name}} and I am {{age}} years old',
  {
    expressionEvaluator(expression: string) {
      return data[expression];
    },
  }
);

console.log(rendered); // My name is Austin and I am 9001 years old

Template where the original computed value type is preserved:

import { renderTemplate } from 'mutton';

const data = {
  age: 9001,
};

const rendered = renderTemplate('{{age}}', {
  expressionEvaluator(expression: string) {
    return data[expression];
  },
});

console.log(rendered, typeof rendered); // 9001 'number'

Compiling

mutton supports compiling the template and then rendering from a compiled template later.

import { compileTemplate, renderCompiledTemplate } from 'mutton';

const data = {
  name: 'Austin',
};

/**
 * {
 *   nodes: [
 *     {
 *       type: 'literal',
 *       literal: 'Hello ',
 *       start: 0,
 *       end: 5
 *     },
 *     {
 *       type: 'expression',
 *       expression: 'name',
 *       start: 6,
 *       end: 13
 *     }
 *   ]
 * }
 */
const compiled = compileTemplate('Hello {{name}}');
const rendered = renderCompiledTemplate(compiled, {
  expressionEvaluator(expression: string) {
    return data[expression]; // Austin
  },
});

console.log(rendered); // Hello Austin

Usage with Jexl

Jexl is a JavaScript expression language and can be used in combination with mutton.

Example:

import jexl from 'jexl';
import { renderTemplate } from 'mutton';

const data = {
  person: {
    name: 'Austin',
    age: 9011,
  },
};

const rendered = renderTemplate(
  'My name is {{person.name}} and I am {{person.age - 10}} years old',
  {
    expressionEvaluator(expression: string) {
      return jexl.evalSync(expression, data);
    },
  }
);

console.log(rendered); // My name is Austin and I am 9001 years old

mutton's People

Contributors

austinkelleher avatar dependabot[bot] avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

Forkers

jweinstein92

mutton's Issues

renderTemplate where expressionEvaluator returns a list

What is the problem

I am using mutton's renderTemplate to evaluate various expressions with the following data object

{
  count: 3,
  data: [
    { id: 1, name: 'name1', value: 'value1' },
    { id: 2, name: 'name2', value: 'value2' },
    { id: 3, name: 'name3', value: 'value3' }, 
  ]
}

Within my expressionEvaluator, I have a JSONata function which takes the data and the expression and will parse it. Depending on the data passed, JSONata will return a value or a list of values. For example, for the expression {{data.id}} my expressionEvaluator would return a list of ids [1, 2, 3].

Running renderTemplate with the expression {{data.id}} and my expressionEvaluator works as expected and renderTemplate returns the list of ids. However, when my expression involves multiple expressions like {{data.name}}::{{data.value}}, the lists get appended together into a string.

Where this is happening

I have determined this is happening in renderCompiledTemplateSync https://github.com/austinkelleher/mutton/blob/master/src/renderCompiledTemplate.ts#L28

In this method, the compiled nodes (in this case of {{data.name}}::{{data.value}} [expression, literal, expression]) is iterating over each one, if it is an expression, running the expressionEvaluator, and then appending it to the previous renderedTemplate as part of a string.

I suppose this makes sense why {{data.id}} works as expected (returning a list of strings) because renderedTemplate is set to the result of the expressionEvaluator.

What I was expecting

If the expressionEvaluator returns an array, I would expect the renderedTemplate to return an array as well. So in this case of an expression containing two expressions evaluating to be arrays, I would expect a single array containing the each expression literal expression combination based on index.

Example code

I have made this code sample to demonstrate the issue https://codesandbox.io/s/mutton-issue-example-tpt2k?file=/src/index.js

Conditions and Loops

Feature Request

I would like the user to be able to build complex templates using conditions and loops.

Examples

const data = {
  names: [
     { name: 'baz', bars: ["baz", "moo"] },
     { name: 'foo' }
  ]
};

with template:

{{ if (names.length) }}
   {{name}}
{{ endif }}

or a loop like:

{{ for (names)}
   {{name}} is a fun name
{{ endfor }}

Additionally, I'm using JSONATA for my processing engine, it could give me some REALLY cool expressions I could do like:

{{ for (names.bars) }}
  {{ this }}
{{ endfor }}

which could result in like: "baz moo".

Problem

I realize this engine doesn't always return strings, so I'm thinking if you scanned it and found those keywords you could say ok this is a string. Additionally, you could say when i find a for/if then pass the arr/obj in the params to the parser.

Alternatives

I found a parser that would like me use mutton + jsonata + mustache (LOL) to make complex string templates like this but it felt ---- odd to say the least.

https://martinholden-skillsoft.github.io/jsonata-extended/doc/module-jsonata-functions.html#~mustache

Allow async expression evaluator when rendering from a compiled template

Proposed API:

import { compileTemplate, renderCompiledTemplateAsync } from 'mutton';

const compiled = compileTemplate('{{hopper}}');

const result = await renderCompiledTemplateAsync(compiled, {
  expressionEvaluator(expression) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(expression);
      }, 100);
    });
  }
});

console.log(result); // hopper

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.