テンプレートエンジンTenjinを使ってみる
ふと、Sinatraで標準対応していないテンプレートエンジンのTenjinを使ってみようと思い、
いろいろ試してみたところ、なんとかいけそうな感じにはなってきた。
Sinatraは内部でTiltという汎用的なテンプレートのインターフェースを使っているが、
それに合わせたクラスにしてやればいいようだ。
test_template.rb:
require 'sinatra' require 'tenjin' class MyEngine < Tenjin::Engine def initialize(path, line, options) @template_path = path super({}) end def render(app, locals, &block) super(@template_path, locals) end end Tilt.register :rbhtml, MyEngine helpers do def tenjin(*args) render(:rbhtml, *args) end end get '/' do tenjin :index, {}, {:foo => 'foo value'} end
実行結果:
hiro@neptune% cat ./views/index.rbhtml <html> <body> ${@foo} </body> </html> hiro@neptune% ruby test_template.rb & [1] 2412 hiro@neptune% == Sinatra/1.1.2 has taken the stage on 4567 for development with backup from Thin >> Thin web server (v1.2.7 codename No Hup) >> Maximum connections set to 1024 >> Listening on 0.0.0.0:4567, CTRL+C to stop hiro@neptune% curl http://localhost:4567 127.0.0.1 - - [13/May/2011 00:23:41] "GET / HTTP/1.1" 200 40 0.0160 <html> <body> foo value </body> </html>