Convert Figma logo to code with AI

mustache logomustache

Logic-less Ruby templates.

3,065
271
3,065
51

Top Related Projects

Minimal templating with {{mustaches}} in JavaScript

Minimal templating on steroids.

21,807

Pug – robust, elegant, feature rich template engine for Node.js

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)

Quick Overview

Mustache is a logic-less templating system that can be used for HTML, config files, source code, and more. It works by expanding tags in a template using values provided in a hash or object. It is available in many programming languages, making it a versatile choice for various projects.

Pros

  • Language-agnostic: Mustache is implemented in multiple programming languages, allowing for consistent templating across different platforms.
  • Simple and lightweight: The syntax is easy to learn and use, with a minimal set of features.
  • Logic-less: Encourages separation of logic from presentation, promoting cleaner and more maintainable code.
  • Widely adopted: Used in many popular projects and supported by various frameworks and libraries.

Cons

  • Limited functionality: The simplicity of Mustache can be a drawback for complex templating needs.
  • No built-in control structures: Lacks traditional if/else statements and loops, which can make some tasks more challenging.
  • Performance: May not be as fast as some other templating engines, especially for large-scale applications.
  • Learning curve for advanced usage: While simple to start with, some advanced techniques may require more effort to master.

Code Examples

  1. Basic variable substitution:
Hello, {{name}}!
  1. Conditional rendering:
{{#show_name}}
  <h1>{{name}}</h1>
{{/show_name}}
  1. Iterating over a list:
<ul>
  {{#items}}
    <li>{{.}}</li>
  {{/items}}
</ul>
  1. Using partials:
{{> header}}
<h1>{{title}}</h1>
<p>{{content}}</p>
{{> footer}}

Getting Started

To use Mustache in a JavaScript project:

  1. Install Mustache via npm:

    npm install mustache
    
  2. Use it in your code:

    const Mustache = require('mustache');
    
    const template = 'Hello, {{name}}!';
    const data = { name: 'World' };
    
    const output = Mustache.render(template, data);
    console.log(output); // Output: Hello, World!
    

For other languages, check the Mustache documentation for specific installation and usage instructions.

Competitor Comparisons

Minimal templating with {{mustaches}} in JavaScript

Pros of mustache.js

  • Specifically designed for JavaScript environments, offering better integration with Node.js and browser-based applications
  • Faster rendering performance in JavaScript contexts
  • Supports asynchronous template loading, beneficial for dynamic web applications

Cons of mustache.js

  • Less language-agnostic compared to the original Mustache implementation
  • May have slight differences in syntax or behavior from the core Mustache spec
  • Smaller community and potentially fewer resources compared to the main Mustache project

Code Comparison

mustache.js:

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

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

Mustache (Ruby example):

view = {
  :title => "Joe",
  :calc => lambda { 2 + 4 }
}

output = Mustache.render("{{title}} spends {{calc}}", view)

Both implementations follow similar syntax and logic, with minor differences in language-specific details. The mustache.js version is tailored for JavaScript, while the original Mustache can be used across various programming languages.

Minimal templating on steroids.

Pros of Handlebars.js

  • More powerful and flexible with built-in helpers and custom helper support
  • Allows for more complex logic and control structures within templates
  • Supports precompilation of templates for better performance

Cons of Handlebars.js

  • Steeper learning curve due to additional features and syntax
  • Slightly larger file size and potentially slower rendering for simple templates
  • Less strict adherence to logic-less templates philosophy

Code Comparison

Mustache:

{{#items}}
  <li>{{name}}</li>
{{/items}}

Handlebars.js:

{{#each items}}
  <li>{{this.name}}</li>
{{/each}}

Key Differences

  1. Syntax: Handlebars.js extends Mustache syntax with additional features.
  2. Helpers: Handlebars.js provides built-in helpers and allows custom helpers.
  3. Logic: Handlebars.js permits more complex logic within templates.
  4. Performance: Mustache is generally faster for simple templates, while Handlebars.js offers precompilation for improved performance in complex scenarios.
  5. Learning Curve: Mustache is simpler to learn, while Handlebars.js requires more time to master its advanced features.

Use Cases

  • Mustache: Ideal for simple, logic-less templates and projects prioritizing simplicity.
  • Handlebars.js: Better suited for complex templates requiring more advanced logic and customization.

Both templating engines have their strengths, and the choice between them depends on project requirements and developer preferences.

21,807

Pug – robust, elegant, feature rich template engine for Node.js

Pros of Pug

  • More powerful and feature-rich templating language
  • Supports mixins, includes, and extends for better code reuse
  • Cleaner, indentation-based syntax that reduces boilerplate

Cons of Pug

  • Steeper learning curve due to its unique syntax
  • Less widespread adoption compared to Mustache
  • Requires compilation step, which can add complexity to the build process

Code Comparison

Pug:

doctype html
html(lang="en")
  head
    title= pageTitle
  body
    h1= pageHeading

Mustache:

<!DOCTYPE html>
<html lang="en">
  <head><title>{{pageTitle}}</title></head>
  <body><h1>{{pageHeading}}</h1></body>
</html>

Summary

Pug offers a more powerful templating language with advanced features and a cleaner syntax, but comes with a steeper learning curve and requires compilation. Mustache, on the other hand, provides a simpler, logic-less templating approach that's easier to learn and doesn't require compilation, but lacks some of the advanced features found in Pug. The choice between the two depends on project requirements, team expertise, and desired templating complexity.

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)

Pros of Nunjucks

  • More powerful and feature-rich, offering advanced templating capabilities like template inheritance and macros
  • Supports asynchronous rendering, which can be beneficial for complex templates or large datasets
  • Provides better control structures and built-in filters for more flexible template manipulation

Cons of Nunjucks

  • Steeper learning curve due to its more extensive feature set
  • Slightly slower rendering performance compared to Mustache's simplicity
  • Larger file size and potentially increased complexity in project setup

Code Comparison

Mustache:

<h1>{{title}}</h1>
<ul>
{{#items}}
  <li>{{name}}</li>
{{/items}}
</ul>

Nunjucks:

<h1>{{ title }}</h1>
<ul>
{% for item in items %}
  <li>{{ item.name }}</li>
{% endfor %}
</ul>

Summary

Nunjucks offers more advanced features and flexibility compared to Mustache, making it suitable for complex templating needs. However, this comes at the cost of a steeper learning curve and potentially slower rendering. Mustache, on the other hand, maintains its simplicity and ease of use, which can be preferable for simpler projects or when performance is a critical factor. The choice between the two depends on the specific requirements of your project and the level of templating complexity you need to handle.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Mustache

Gem Version Build Status

Inspired by ctemplate and et, Mustache is a framework-agnostic way to render logic-free views.

As ctemplates says, "It emphasizes separating logic from presentation: it is impossible to embed application logic in this template language."

For a list of implementations (other than Ruby) and tips, see http://mustache.github.io/.

Overview

Think of Mustache as a replacement for your views. Instead of views consisting of ERB or HAML with random helpers and arbitrary logic, your views are broken into two parts: a Ruby class and an HTML template.

We call the Ruby class the "view" and the HTML template the "template."

All your logic, decisions, and code is contained in your view. All your markup is contained in your template. The template does nothing but reference methods in your view.

This strict separation makes it easier to write clean templates, easier to test your views, and more fun to work on your app's front end.

Why?

I like writing Ruby. I like writing HTML. I like writing JavaScript.

I don't like writing ERB, Haml, Liquid, Django Templates, putting Ruby in my HTML, or putting JavaScript in my HTML.

Installation

Install the gem locally with:

$ gem install mustache

Or add it to your Gemfile:

gem "mustache", "~> 1.0"

Usage

Quick example:

>> require 'mustache'
=> true
>> Mustache.render("Hello {{planet}}", planet: "World!")
=> "Hello World!"

We've got an examples folder but here's the canonical one:

class Simple < Mustache
  def name
    "Chris"
  end

  def value
    10_000
  end

  def taxed_value
    value * 0.6
  end

  def in_ca
    true
  end
end

We simply create a normal Ruby class and define methods. Some methods reference others, some return values, some return only booleans.

Now let's write the template:

Hello {{name}}
You have just won {{value}} dollars!
{{#in_ca}}
Well, {{taxed_value}} dollars, after taxes.
{{/in_ca}}

This template references our view methods. To bring it all together, here's the code to render actual HTML;

Simple.render

Which returns the following:

Hello Chris
You have just won 10000 dollars!
Well, 6000.0 dollars, after taxes.

Simple.

Tag Types

For a language-agnostic overview of Mustache's template syntax, see the mustache(5) manpage or http://mustache.github.io/mustache.5.html.

Escaping

Mustache does escape all values when using the standard double Mustache syntax. Characters which will be escaped: & \ " < > (as well as ' in Ruby >= 2.0). To disable escaping, simply use triple mustaches like {{{unescaped_variable}}}.

Example: Using {{variable}} inside a template for 5 > 2 will result in 5 &gt; 2, where as the usage of {{{variable}}} will result in 5 > 2.

Dict-Style Views

ctemplate and friends want you to hand a dictionary to the template processor. Mustache supports a similar concept. Feel free to mix the class-based and this more procedural style at your leisure.

Given this template (winner.mustache):

Hello {{name}}
You have just won {{value}} bucks!

We can fill in the values at will:

view = Winner.new
view[:name] = 'George'
view[:value] = 100
view.render

Which returns:

Hello George
You have just won 100 bucks!

We can re-use the same object, too:

view[:name] = 'Tony'
view.render # => Hello Tony\nYou have just won 100 bucks!

Templates

A word on templates. By default, a view will try to find its template on disk by searching for an HTML file in the current directory that follows the classic Ruby naming convention.

TemplatePartial => ./template_partial.mustache

You can set the search path using Mustache.template_path. It can be set on a class by class basis:

class Simple < Mustache
  self.template_path = __dir__
end

Now Simple will look for simple.mustache in the directory it resides in, no matter the cwd.

If you want to just change what template is used you can set Mustache.template_file directly:

Simple.template_file = './blah.mustache'

Mustache also allows you to define the extension it'll use.

Simple.template_extension = 'xml'

Given all other defaults, the above line will cause Mustache to look for './blah.xml'

Feel free to set the template directly:

Simple.template = 'Hi {{person}}!'

Or set a different template for a single instance:

Simple.new.template = 'Hi {{person}}!'

Whatever works.

Views

Mustache supports a bit of magic when it comes to views. If you're authoring a plugin or extension for a web framework (Sinatra, Rails, etc), check out the view_namespace and view_path settings on the Mustache class. They will surely provide needed assistance.

Helpers

What about global helpers? Maybe you have a nifty gravatar function you want to use in all your views? No problem.

This is just Ruby, after all.

module ViewHelpers
  def gravatar
    gravatar_id = Digest::MD5.hexdigest(self[:email].to_s.strip.downcase)
    gravatar_for_id(gravatar_id)
  end

  def gravatar_for_id(gid, size = 30)
    "#{gravatar_host}/avatar/#{gid}?s=#{size}"
  end

  def gravatar_host
    @ssl ? 'https://secure.gravatar.com' : 'http://www.gravatar.com'
  end
end

Then just include it:

class Simple < Mustache
  include ViewHelpers

  def name
    "Chris"
  end

  def value
    10_000
  end

  def taxed_value
    value * 0.6
  end

  def in_ca
    true
  end

  def users
    User.all
  end
end

Great, but what about that @ssl ivar in gravatar_host? There are many ways we can go about setting it.

Here's an example which illustrates a key feature of Mustache: you are free to use the initialize method just as you would in any normal class.

class Simple < Mustache
  include ViewHelpers

  def initialize(ssl = false)
    @ssl = ssl
  end
end

Now:

Simple.new(request.ssl?).render

Finally, our template might look like this:

<ul>
  {{# users}}
    <li><img src="{{ gravatar }}"> {{ login }}</li>
  {{/ users}}
</ul>

Integrations

Sinatra

Sinatra integration is available with the mustache-sinatra gem.

An example Sinatra application is also provided: https://github.com/defunkt/mustache-sinatra-example

If you are upgrading to Sinatra 1.0 and Mustache 0.9.0+ from Mustache 0.7.0 or lower, the settings have changed. But not that much.

See this diff for what you need to do. Basically, things are named properly now and all should be contained in a hash set using set :mustache, hash.

Rack::Bug

Mustache also provides a Rack::Bug panel. First you have to install the rack-bug-mustache_panel gem, then in your config.ru add the following code:

require 'rack/bug/panels/mustache_panel'
use Rack::Bug::MustachePanel

Using Rails? Add this to your initializer or environment file:

require 'rack/bug/panels/mustache_panel'
config.middleware.use "Rack::Bug::MustachePanel"

Rack::Bug

Vim

vim-mustache-handlebars is available at mustache/vim-mustache-handlebars

Emacs

mustache-mode.el is available at mustache/emacs

TextMate

Mustache.tmbundle

See https://gist.github.com/defunkt/323624 for installation instructions.

Command Line

See mustache(1) man page or http://mustache.github.io/mustache.1.html for command line docs.

Acknowledgements

Thanks to Tom Preston-Werner for showing me ctemplate and Leah Culver for the name "Mustache."

Special thanks to Magnus Holm for all his awesome work on Mustache's parser.

Contributing

Once you've made your great commits:

  1. Fork Mustache
  2. Create a topic branch - git checkout -b my_branch
  3. Push to your branch - git push origin my_branch
  4. Create an Issue with a link to your branch
  5. That's it!

Mailing List

~~To join the list simply send an email to mustache@librelist.com. This will subscribe you and send you information about your subscription, including unsubscribe information.

The archive can be found at http://librelist.com/browser/mustache/.~~

The mailing list hasn't been updated in quite a while, please join us on Gitter or IRC:

Join the chat at https://gitter.im/mustache/mustache

#{ on Freenode

Meta

NPM DownloadsLast 30 Days