DEV Community

Davide Santangelo
Davide Santangelo

Posted on • Edited on

Logic-less Ruby templates with Mustache

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'
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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}}.
Enter fullscreen mode Exit fullscreen mode

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

 GitHubProfile.new(user).render(template)
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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)