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

usematch

v1.7.3

Published

An anagram of Mustache. Mustache on acid = Richer templates

Downloads

11

Readme

usematch

An anagram of Mustache

npm Package build status

Features

This is a code/template compatible replacement for mustache. T

It has a lot more flexibility over the original engine:

  • An {{else}} block for #ifish blocks and ^not-ifish blocks:

    • {{#value} ... {{else} ... {{/value}
    • {{^value} ... {{else}} ... {{/value}}
  • default context values for everything, defined in the template:

    • {{name {name:'John Doe'} }}
    • {{#posts {bg_image:'/images/bg.jpg'} }}
    • {{>post_page {author: 'John Doe'} }}
    • See also references below
  • filters on everything:

    • {{name #toUpper}} or {{name | toUpper}}: (synonymous)

      eg: var o = {
      	name: "John Doe",
      	toUpper: function(value) { return value.toUpperCase(); }; // 'JOHN DOE'
      }
    • {{title #xmlEscape}}, or {{#posts #xmlEscape}}, or {{>posts #xmlEscape}}

      for var o = {
      	posts: [
      		{title:'first post' ... },
      		{title:'second post' ... }
      	],
      	xmlEscape: function(text) { return text.replace(/&/g, '&')....; }; 
      }
    • parameters, eg. {{tags | split{char:','} | join }}

      for var o = {
      	tags: 'tag1, tag2, tag3',
      	split: function(text, params) { 
      		return text.split(params.char||',').map(
      				function(s) { return s.trim(); }); 
      		}, 
      	join: function(ar, params) { return ar.join(params.char||' | '); },
      }
  • data filters on sections:

    • {{#posts @dataFilter}}{{title}}{{/posts}}

      eg: var o = {
      	posts: [
      		{title:'first post', bg_image:'/images/custom_bg.jpg', ... },
      		{title:'second post' ... }
      	],
      	dataFilter: function(posts, params) { 
      		return posts.slice(0,1).map(function(post) { return post.title.toUpperCase(); });
      	};
      }
    • Automagic data filtering with prefilter.<section>. eg. {{#posts}}{{title}}{{/posts}}:

      eg: var o = {
      	posts: [ ... ],
      	prefilter: {
      		posts: function(posts, params) { 
      			return posts.slice(0,1).map(function(post) { return post.title.toUpperCase(); });
      		}
      	}
      	// OR:
      	// 'prefilter.posts' : function(....
      }
    • Parameters to data filters {{#posts @customFilter{len:10} }}{{title}}{{/posts}}

      eg: var o = {
      	posts: [ ... ],
      	customFilter: function(posts, params) { 
      		return posts.slice(0,params.len || 5);
      	};
      }
  • sections can be functions too (like mustache). (They must return either a string, OR an array of objects):

    • {{#posts}} ... {{/posts}}

      eg: var o = {
      	posts: function() { 
      		return [
      				{title:'first post' ... },
      				{title:'second post' ... }
      			] 
      		}
      	}

      Or, return a 'renderable' item:

      eg: var o = {
      	posts: function() { return function(text, render, elseText) {
      		return render( "some fantastic {{title}}", 
      				[			
      					{title:'first post' ... },
      					{title:'second post' ... }
      				] 					
      			 );
      		}}
      	}
  • Iterate any object by key/value:

    • {{#tags.*}}Tag:{{key}} Items:{{#value}}{{title}}{{/value}}{{/tags.*}}
      eg: var o = {
      		tags: {
      			tag1: [
      				{title:'first post'},
      				{title:'2nd post'},
      			],
      			tag2: [
      				{title:'first post'},
      				{title:'3rd post'},
      			]
      		}
      	}
  • References:

    • default contexts can also be a reference {{#posts &default_post}}{{upperTitle}}{{/posts}}:
      eg: var o = {
      		posts: [
      			{title:'first post', bg_image:'/images/custom_bg.jpg', ... },
      			{title:'second post' ... }
      		],
      		default_post: {
      			bg_image: '/images/bg.jpg'
      			upperTitle: function() { return this.title.toUpperCase() } // eg. 'FIRST POST'
      		}
      	}
    • include/partials as a reference {{> &menu_name }}:
      eg: var o = {
      		menu_name: "navbar-menu.html"
      	}
  • Fallback values. Rather than using {{#val}}{{val}}{{else}}{{othervalue}}{{/val}} use:

    • {{val || othervalue}}

Usage

const usematch = require('usematch');

console.log(usematch.render('{{title}}', {title:"Awesome!"})); 
// prints 'Awesome!'

For a complete 'drop-in' replacement api of mustache, use:

var Mustache = require('usematch').mustache;

... (your existing code works here without change) ...

API

There are actually two API's provided by this package. Usematch's own and a code compatible Mustache one. Use the latter when porting an existing project. It is recommended to use the Usematch API if you want to be able have tighter control over the system (as there are a lot more options you can tweak).

Usematch API

var usematch = require("usematch");

var context = {
  title: "Joe",
  calc: function () {
    return 2 + 4;
  }
};

var output = usematch.render("{{title}} spends {{calc}}", context);

Following is an rtype signature of the most commonly used functions.

usematch.render(
  template  : String|Tokens,
  context   : Object,
  options?  : Options
) => String

usematch.parse(
  template   : String,
  options?   : Options
) => Tokens

interface Tokens [ Object ];

interface Options { 		// All elements are optional
	tag_start : "{{",
	tag_end   : "}}",
	partials  : Object 		// used with {{> partial_name }}
	defaults  : Object 		// used in conjuction with the 'context' parameter of render()
}

Mustache Compatible API

Usematch uses mustache's own tests to ensure this compatibility is real and effective, and is checked automatically as part of travis.

var Mustache = require("usematch").mustache;

var context = {
  title: "Joe",
  calc: function () {
    return 2 + 4;
  }
};

var output = Mustache.render("{{title}} spends {{calc}}", context);

Following is an rtype signature of the most commonly used functions.

Mustache.render(
  template  : String,
  context   : Object,
  partials? : Object,
) => String

Mustache.parse(
  template              : String,
  tags = ['{{', '}}']   : Tags,
) => String

interface Tags [String, String]

See the original mustache documentumentation.

Differences

Caching

Usematch doesn't try and cache things for you, by default. This can be a huge memory saving in some instances. However, when you use require('usematch').mustache, then a basic cache will be activated that works similarly to mustache's original.

You must save the return value of the parse function, in order to save execution time. You could even spool the tokens to disk for later use, if you like.

var tokens = usematch.parse('{{title}}');
var text = usematch.render(tokens, { data: ...})

Whitespace

Mustache does some pretty crazy things in order to reduce the generated whitespace. This can be problematic if not rendering HTML, so usematch doesn't try to do this. If you want to clean up the returned text, then something like this should suffice:

// eat all whitespace that appear more than once in a sequence
text = text.replace(/\s{2,}/g, ' '); 

Or:

// remove all whitespace around newlines. (this also reduces \n\n)
text = text.replace(/\s*\n\s*/g, '\n'); 

Why?

When writing a new CMS package, I was dismayed how mustache failed to suit my needs, despite the impressive following it has. Mostly, was the lack of the ability to set 'defaults', which was a complete deal breaker for me. Although not a fan of mustache's double handlebar syntax, I understood however that others were very happy with the formatting. Hence, this drop in mustache compatible alternative was created. Feel free to fork, or add comments, or report bugs.