Why ERB embedded in Javascript is wrong

February 11, 2011

Javascript with embedded erb is used by most, if not all, Rails developers. Here is an example:

  greeting = function() {
    return "Hi,<%= name %>"
  }

Stop doing this!

Why? Let's look at the Ruby counterpart of the above example:

  # greeting.rb
  def greeting
    "Hi, <%= name %>"
  end

  # Now let's executing the file
  require 'erb'

  name = "Bruce"
  str = File.read('greeting.rb')
  result = ERB.new(str).result(binding)

  eval(result)

  greeting # => "Hi, Bruce" 

Here are better ways to write the greeting function in both languages. So stop the madness. No ERB in Javascript please!

blog comments powered by Disqus

© 2011 Rit Li