Make templating great again with mustache
!
Mustache separates your logic code from the view code that is displayed to your user. This means you can change your presentation however you please, without affecting your data.
Demo the awesomeness of this gem!
After you gem install mustache
, go into pry
and type:
require 'mustache'
=> true
Create the logic
Make a class that inherits from the parent class Mustache, then add your logic, each as a separate class method:
A most fascinating example has been provided below:
class Profile < Mustache
def name
"Daryl"
end
def age
22 + 7
end
def hometown
"Hayward"
end
def has_mustache?
true
end
end
Create the view
To retrieve and render data from our newly-created class, we'll use our class name along with the .render
method. We call class methods within double curly braces, which look kinda like curly mustaches (thus the gem name mustache!!!
)
Profile.render("Hello, my name is {{name}}.")
=> "Hello, my name is Daryl."
Profile.render("I am {{age}} years old.")
=> "I am 29 years old."
Profile.render("I live in {{hometown}}.")
=> "I live in Hayward."
Profile.render("{{#has_mustache?}}I have a mustache.{{/has_mustache?}}")
=> "I have a mustache."
What would happen if we set the class method has_mustache?
to false?
Class Babyface < Mustache
def has_mustache?
false
end
end
Now when we try to render the string:
Babyface.render("{{#has_mustache?}}I have a mustache.{{/has_mustache?}}")
What's our result?
This gist and lightning talk are merely the tip of the iceberg as far as what Mustache is capable of. For starters, it could replace ERB if you prefer to write clean, logic-less HTML code. It could take an entire morning to walk through setting up and implementing Mustache in a Rails setting, but feel free to explore using the demos and documentation provided by the developers of Mustache.