2009-08-15 75 views
8

我正在嘗試在液體佈局(Liquid Template lang,不是CSS液體佈局的東西)內渲染液體模板。我似乎無法得到佈局部分呈現。目前正在使用:如何使用Liquid模板語言在佈局中渲染模板?

assigns = {'page_name' => 'test'} 
@layout = Liquid::Template.parse(File.new(@theme.layout.path).read) 
@template = Liquid::Template.parse(File.new(self.template.path).read) 

@rend_temp = @template.render(assigns) 
@rend_layout = @layout.render({'content_for_layout' => @rend_temp}) 

render :text => @rend_layout, :content_type => :html 

產生的頁面的HTML顯示,「模板」呈現在液體很好,但它不與佈局包裹(與渲染的模板替換「content_for_layout」佈局)

回答

7

只是爲了讓其他人知道誰遇到了這個問題,上面貼出的代碼實際上確實有效,問題在於名爲@template的變量。我將@template和@layout重命名爲@_tempalte和@_layout,並且所有內容都按預期工作。

+0

是的,但有模板查找和你從你上面的代碼放棄繼承鐵軌其他東西的一些劫持。雖然它起作用,但它的風格或功能並不完全是「rails-ish」。 – Dan 2013-03-26 18:22:14

2

使用Ruby使用液體在軌道上(尤其是軌道3) - 我認爲適當的方式來呈現你的液模板(也保持所有的工作軌道爲你做的)如下...

液體寶石本身爲導軌提供液體視圖,因此當您調用#render時,您可以將導軌連接起來以查找「液體」模板。這liquid_view只能完全軌2.3 但可以很容易地進行以下更新

if content_for_layout = @view.instance_variable_get("@content_for_layout") 
    assigns['content_for_layout'] = content_for_layout 
elsif @view.content_for?(:layout) 
    assigns["content_for_layout"] = @view.content_for(:layout) 
end 
assigns.merge!(local_assigns.stringify_keys) 

這可以在這裏看到更新與軌道3合作 - >https://github.com/danshultz/liquid/commit/e27b5fcd174f4b3916a73b9866e44ac0a012b182

然後正確地呈現你的液鑑於只需撥打

render :template => "index", :layout => "my_layout", :locals => { liquid_drop1 => drop, liquid_drop2 => drop } 

在我們的應用程序,因爲我們有共同的液體屬性的少數,我們重寫了「渲染」的方法在我們的基地控制器自動包括由R默認當地人eferencing #liquid_view_assigns其捲起另外加入的液滴的渲染調用

def render(...) 
    options[:locals] = options.fetch(:locals, {}).merge(liquid_view_assigns) 
    super 
end