Module: Sinatra
- Defined in:
- lib/sinatra/jstpages.rb,
lib/sinatra/backbone.rb
Overview
JstPages [module]
A Sinatra plugin that adds support for JST (JavaScript Server Templates). See JstPages example for a full example application.
Basic usage
Register the Sinatra::JstPages plugin in your application, and use
serve_jst. This example serves all JST files found in /views/**/*.jst.*
(where /views is your views directory as defined in Sinatra's
settings.views) as http://localhost:4567/jst.js.
require 'sinatra/jstpages'
class App < Sinatra::Base
register Sinatra::JstPages
serve_jst '/jst.js'
end
You will need to link to the JST route in your layout. Make a <script> tag
where the src='...' attribute is the same path you provide to serve_jst.
<script type='text/javascript' src='/jst.js'></script>
So, if you have a JST view placed in views/editor/edit.jst.tpl:
# views/editor/edit.jst.tpl
<h1>Edit <%= name %></h1>
<form>
<button>Save</button>
</form>
Now in your browser you may invoke JST['templatename']:
// Renders the editor/edit template
JST['editor/edit']();
// Renders the editor/edit template with template parameters
JST['editor/edit']({name: 'Item Name'});
Using Sinatra-AssetPack?
TIP: If you're using the sinatra-assetpack gem, just add /jst.js
to a package. (If you're not using Sinatra AssetPack yet, you probably
should.)
Supported templates
Jade (.jst.jade) -- Jade templates. This requires
jade.js. For older browsers, you will also need json2.js,
and an implementation of String.prototype.trim.
# views/editor/edit.jst.jade
h1= "Edit "+name
form
Save
Underscore templates (.jst.tpl) -- Simple templates by
underscore. This requires underscore.js, which Backbone also
requires.
# views/editor/edit.jst.tpl
<h1>Edit <%= name %></h1>
<form>
<button>Save</button>
</form>
Haml.js (.jst.haml) -- A JavaScript implementation of Haml.
Requires haml.js.
# views/editor/edit.jst.haml
h1= "Edit "+name
form
Save
Eco (.jst.eco) -- Embedded CoffeeScript templates. Requires
eco.js and coffee-script.js.
# views/editor/edit.jst.eco
<h1>Edit <%= name %></h1>
<form>
<button>Save</button>
</form>
You can add support for more templates by subclassing the Engine class.