2011-05-18 37 views
4

我想擁有獨立的.markdown文件,然後將其包含在我的haml模板中。所以我想以某種方式包含 - 不渲染 - 一個外部文件到模板中。我希望父文件在其中包含:markdown,直接包含在其下面,然後.markdown文件只是純粹的降價。如何將任意文件包含到HAML模板中?

或者:有沒有一種方法可以使用markdown作爲rails模板語言(同樣我可以在erb或haml和rails中編寫模板或partials)

回答

2

我能想到的最簡單的方法是針對Markdown的create a custom template handler。你可以使用Markdown代碼作爲partials(也可以免費獲得當地人的支持)。

module Markdown 
    class Template < ActionView::Template::Handler 
    include ActionView::Template::Handlers::Compilable 

    self.default_format = Mime::HTML 

    def compile(template) 
     '"' + Maruku.new(template.source).to_html + '".html_safe' 
    end 
    end 
end 

然後用降價的擴展名(在application.rb中或自定義初始化)進行註冊:

ActionView::Template.register_template_handler(:md, Markdown::Template) 

然後用戶呈現,就像您對任何部分:)

# for file foo.md 
= render 'foo' 
0

這是我能拿出(在所有涉及沒有HAML過濾器)最好的:

=raw Maruku.new(File.read(File.dirname(__FILE__)+'/foo.markdown')).to_html 
0

這事我問HAML開發商而回。我建議我們需要一個用於HAML的:include過濾器。他們的迴應是,我們應該將文件加載到變量中,然後像使用其他變量一樣使用變量。

4

這與您的解決方案類似,但使用了:markdown過濾器。 Haml對任何過濾的文本執行字符串插值,因此您可以像這樣讀取降價文件。

:markdown 
    #{File.read(File.join(File.dirname(__FILE__), "foo.markdown"))} 

你可以把它放到幫助器中,但是你必須小心文件路徑。

+0

哦~~不錯,比我好多了。 – 2011-05-19 15:11:53

0

至少在Rails 3.1.0中不推薦使用擴展ActionView::Template::Handler。不要使用以下工作對我來說:

lib/markdown_views.rb

require "rdiscount" 

class MarkdownViews 

    def call template 
    'md = ERB.new(<<\'EOF\'%s 
EOF 
).result(binding) 
    RDiscount.new(md).to_html.html_safe'% template.source 
    end 

end 

config/application.rb

require "markdown_views" 
ActionView::Template.register_template_handler :markdown, MarkdownViews.new 

views/public/home.html.markdown

# H1 

    + Bullets. 
    + screaming. 
    + from out of nowhere 

<%= "Embedded Ruby" %> 
相關問題