loading...
Chorally

Logic-less Ruby templates with Mustache

daviducolo profile image Davide Santangelo Updated on ・2 min read

These days I'm working on a new feature for the product of the company (Chorally) I work for.

In this regard, I'm developing our own templating language. To do this I'm using the mustache framework.

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.

Posted on by:

daviducolo profile

Davide Santangelo

@daviducolo

developer - dad. APIs specialist, In love with #ruby, #rails and #python - developer at @getchorally

Chorally

The customer engagement platform Get in touch with your customers in the moments that matter.

Discussion

markdown guide