- Notifications
You must be signed in to change notification settings - Fork268
mustache/mustache
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Inspired byctemplate andet, Mustache is aframework-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, seehttp://mustache.github.io/.
Think of Mustache as a replacement for your views. Instead of viewsconsisting of ERB or HAML with random helpers and arbitrary logic,your views are broken into two parts: a Ruby class and an HTMLtemplate.
We call the Ruby class the "view" and the HTML template the"template."
All your logic, decisions, and code is contained in your view. Allyour markup is contained in your template. The template does nothingbut 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.
I like writing Ruby. I like writing HTML. I like writing JavaScript.
I don't like writing ERB, Haml, Liquid, Django Templates, putting Rubyin my HTML, or putting JavaScript in my HTML.
Install the gem locally with:
$ gem install mustache
Or add it to yourGemfile
:
gem"mustache","~> 1.0"
Quick example:
>> require 'mustache'=> true>> Mustache.render("Hello {{planet}}", planet: "World!")=> "Hello World!"
We've got anexamples
folder but here's the canonical one:
classSimple <Mustachedefname"Chris"enddefvalue10_000enddeftaxed_valuevalue *0.6enddefin_catrueendend
We simply create a normal Ruby class and define methods. Some methodsreference 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 ChrisYou have just won 10000 dollars!Well, 6000.0 dollars, after taxes.
Simple.
For a language-agnostic overview of Mustache's template syntax, seethemustache(5)
manpage orhttp://mustache.github.io/mustache.5.html.
Mustache does escape all values when using the standard doubleMustache syntax. Characters which will be escaped:& \ " < >
(aswell as'
in Ruby>= 2.0
). To disable escaping, simply use triplemustaches like{{{unescaped_variable}}}
.
Example: Using{{variable}}
inside a template for5 > 2
willresult in5 > 2
, where as the usage of{{{variable}}}
willresult in5 > 2
.
ctemplate and friends want you to hand a dictionary to the templateprocessor. Mustache supports a similar concept. Feel free to mix theclass-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.newview[:name]='George'view[:value]=100view.render
Which returns:
Hello GeorgeYou 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!
A word on templates. By default, a view will try to find its templateon disk by searching for an HTML file in the current directory thatfollows the classic Ruby naming convention.
TemplatePartial => ./template_partial.mustache
You can set the search path usingMustache.template_path
. It can be set on aclass by class basis:
classSimple <Mustacheself.template_path=__dir__end
NowSimple
will look forsimple.mustache
in the directory it residesin, no matter the cwd.
If you want to just change what template is used you can setMustache.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 lookfor './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.
Mustache supports a bit of magic when it comes to views. If you'reauthoring a plugin or extension for a web framework (Sinatra, Rails,etc), check out theview_namespace
andview_path
settings on theMustache
class. They will surely provide needed assistance.
What about global helpers? Maybe you have a niftygravatar
functionyou want to use in all your views? No problem.
This is just Ruby, after all.
moduleViewHelpersdefgravatargravatar_id=Digest::MD5.hexdigest(self[:email].to_s.strip.downcase)gravatar_for_id(gravatar_id)enddefgravatar_for_id(gid,size=30)"#{gravatar_host}/avatar/#{gid}?s=#{size}"enddefgravatar_host@ssl ?'https://secure.gravatar.com' :'http://www.gravatar.com'endend
Then just include it:
classSimple <MustacheincludeViewHelpersdefname"Chris"enddefvalue10_000enddeftaxed_valuevalue *0.6enddefin_catrueenddefusersUser.allendend
Great, but what about that@ssl
ivar ingravatar_host
? There aremany ways we can go about setting it.
Here's an example which illustrates a key feature of Mustache: youare free to use theinitialize
method just as you would in anynormal class.
classSimple <MustacheincludeViewHelpersdefinitialize(ssl=false)@ssl=sslendend
Now:
Simple.new(request.ssl?).render
Finally, our template might look like this:
<ul> {{# users}} <li><img src="{{ gravatar }}"> {{ login }}</li> {{/ users}}</ul>
Sinatra integration is available with themustache-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 Mustache0.7.0 or lower, the settings have changed. But not that much.
Seethis diff for what you need todo. Basically, things are named properly now and all should becontained in a hash set usingset :mustache, hash
.
Mustache also provides aRack::Bug
panel.First you have to install therack-bug-mustache_panel
gem, then in yourconfig.ru
add the following code:
require'rack/bug/panels/mustache_panel'useRack::Bug::MustachePanel
Using Rails? Add this to your initializer or environment file:
require'rack/bug/panels/mustache_panel'config.middleware.use"Rack::Bug::MustachePanel"
vim-mustache-handlebars is available atmustache/vim-mustache-handlebars
mustache-mode.el is available atmustache/emacs
Seehttps://gist.github.com/defunkt/323624 for installation instructions.
Seemustache(1)
man page orhttp://mustache.github.io/mustache.1.htmlfor command line docs.
Thanks toTom Preston-Werner for showingme ctemplate andLeah Culver for the name "Mustache."
Special thanks toMagnus Holm for all hisawesome work on Mustache's parser.
Once you've made your great commits:
- Fork Mustache
- Create a topic branch -
git checkout -b my_branch
- Push to your branch -
git push origin my_branch
- Create anIssue with a link to your branch
- That's it!
~~To join the list simply send an email tomustache@librelist.com. Thiswill subscribe you and send you information about your subscription,including unsubscribe information.
The archive can be found athttp://librelist.com/browser/mustache/.~~
The mailing list hasn't been updated in quite a while, please join us on Gitteror IRC:
#{ on Freenode
- Code:
git clone https://github.com/mustache/mustache.git
- Home:http://mustache.github.io
- Bugs:https://github.com/mustache/mustache/issues
- List:mustache@librelist.com
- Gems:https://rubygems.org/gems/mustache