Skip to content

Instantly share code, notes, and snippets.

@davetheninja
Created September 10, 2011 07:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davetheninja/1208086 to your computer and use it in GitHub Desktop.
Save davetheninja/1208086 to your computer and use it in GitHub Desktop.
Javascript templating solution
tamplates.js.coffee
----------------------
class window.Templates
@templates = {}
@add: (name, template) ->
@templates[name] = template
@apply:(name, context) ->
_.template(@templates[name], context)
templates.rake
---------------------
require 'rubygems'
require 'fileutils'
namespace :templates do
task :compile => [:environment] do
app_folder = File.join(Rails.root.to_s, "app")
raw_templates = File.join(app_folder, "templates", "javascripts", "*.underscore")
compiled_templates = File.join(app_folder, "assets", "javascripts", "compiled_templates.js")
File.open(compiled_templates, 'w') do |file|
Dir[raw_templates].each do |template|
template_json = File.read(template).to_json
compiled = "Templates.add('#{File.basename(template, ".underscore")}', #{template_json});"
file.puts compiled
end
end
end
end
application.js
--------------------
// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require underscore
//= require backbone
//= require templates
//= require compiled_templates
//= require reference
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment