Skip to content
A one-method templating "engine" for Ruby. The stupidest thing that could possibly work.
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.

StupidLittleTemplate is a really dumb templating "system" currently clocking in under 20 lines. It has no dependencies and is probably horribly dangerous to use under any circumstances.


require 'stupid_little_template'
include StupidLittleTemplate

# sltmpl takes a template string and "compiles" it into a Proc. The second
# parameter must be a Binding object.
tmpl = sltmpl 'I like to eat :food in :city.', binding

food = 'pizza'
city = 'Chicago'

# Call yield on the Proc and the resulting text is returned.
tmpl.yield  # => I like to eat pizza in Chicago.

# Change variables in the local scope...
food = 'spaghetti'
city = 'Rome'

# ...and call yield again and the new values come out in the text.
tmpl.yield  # => I like to eat spaghetti in Rome.

Yep, it plucks variables right out of the local scope. You can do it with all kinds of variables:

Constant    = 'My'
$global_var = 'name'

class Klass
  include StupidLittleTemplate

  @instance_var = 'is'
  @@class_var   = 'StupidLittleTemplate'

  def foo
    sltmpl ':Constant :$global_var :@instance_var :@@class_var', binding

k = # => My name is StupidLittleTemplate

Hilariously reckless!

You can do some interesting(ish) things with binding, though:

class Klass
  def initialize name, age
    @name = name
    @age  = age

  def my_binding

k = 'Alice', 29

sltmpl("My name is :@name and I'm :@age years old.", k.my_binding).yield
# => My name is Alice and I'm 29 years old.


  • Q: Can you do anything neat with logic in the templates?

    A: Nope.

  • Q: Is this just a stupid toy?

    A: Yep.

  • Q: What happens if I do this:

    stupid = sltmpl ':fooquux:bar', binding
    foo = 'FOO'; bar = 'BAR'

    A: You get :fooquuxBAR. There's a failing test for this.

  • Q: Can I pass in a Hash of values instead of exposing all the locals?

    A: If it could do that I might not have named it StupidLittleTemplate. If you really want, though:

    class Hash
      def my_binding; binding; end
      def method_missing meth, *args
        self[meth] || super
      def respond_to? meth; self[meth] || super; end
    params = { food: 'cheese', city: 'Milwaukee' }
    sltmpl 'I eat :food in :city.', params.my_binding
    # => I eat cheese in Milwaukee.
    But that's just ridiculous.


The regular expression for extracting template variables is adapted from this StackOverflow answer by rjk.

You can’t perform that action at this time.