Mustache is a logic-less template engine for Ruby that is typically used for rendering simple data structures onto templates. With Mustache, the data being rendered is separated from the templates themselves, making it easy to manage complex data sets and re-use templates.
To use Mustache in Ruby, you first need to install the mustache gem:
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."
To test it I created this snippet of code that takes a GitHub account and generates its profile in text form.
I'll use the ruby mustache gem and the octokit gem to extract data from github.
Let's start by extracting the data from GitHub
require 'octokit'
require 'mustache'
client = Octokit::Client.new
user = client.user 'davidesantangelo'
Now, I simply create a normal Ruby class and define methods. Some methods reference others, some return values, some return only booleans.
class GitHubProfile < Mustache
attr_reader :user
def initialize(user)
@user = user
end
def name
user.name
end
def biography
user.bio
end
def location
user.location
end
def blog
user.blog
end
def html_url
user.html_url
end
def hireable
user.hireable ? "i'm available for hiring" : "i'm not available for hiring"
end
end
Now let's write the template:
Hi, i’m {{name}} a {{ biography }}, i living in {{location}}.
You can reach me at {{blog}} or at my github's profile {{html_url}}.
If you are from the HR team, {{hireable}}.
This template references our view methods. To bring it all together, here's the code to render actual HTML;
GitHubProfile.new(user).render(template)
Which returns the following:
Hi, I’m Davide Santangelo a developer - dad. In love with #ruby, #rails, and #python - developer at @chorally, I living in Foggia, Italy.
You can reach me at www.davidesantangelo.com or at my Github's profile https://github.com/davidesantangelo.
If you are from the HR team, I'm not available for hire.
For a language-agnostic overview of Mustache's template syntax, see the mustache(5) manpage or http://mustache.github.io/mustache.5.html.
Obviously this is a little snippet to show the potential of this very cute framework.
Top comments (0)