簡體   English   中英

Sinatra渲染紅寶石文件

[英]Sinatra render a ruby file

例如,如何呈現一個ruby文件(在我的情況下返回一個pdf文檔):

 get "/pdf" do
  @locals = {some_locals_hash}
  headers({'Content-Type' => 'application/pdf',
    'Content-Description' => 'File Transfer',
    'Content-Transfer-Encoding' => 'binary',
    'Content-Disposition' => "attachment;filename=\"test.pdf\"",
    'Expires' => '0',
    'Pragma' => 'public'})
  ruby :test, :layout => false, :locals => @locals
 end

我知道Tilt沒有ruby模板。 現在,我將所有內容都放在*.haml文件中,例如:

 -# PDF file description
 :ruby
   pdf = Prawn::Document.new(
     ... docs settings)
     ... docs content
   end
 = pdf.render()

我用haml :template ...etc...渲染它

事實是,我只需要用它來突出顯示語法,我的編輯器就不能正確地突出haml文件中的嵌入式ruby代碼:(。因此,如果要復雜的話,請不要打擾...

我使用Tilt模板進行管理

module Tilt
  class RubyTemplate < Template
    def prepare
    end

    def evaluate(scope, locals, &block)
      super(scope, locals, &block)
    end

    def precompiled_template(locals)
      data.to_str
    end
  end
  register 'rb', RubyTemplate
end

並使用輔助方法

helpers do
  def ruby(*args) 
    render(:rb, *args) 
  end
end

我不確定這是最好的方法,但至少可以正常工作:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM