【问题标题】:How can you render a template within a layout using Liquid template language?如何使用 Liquid 模板语言在布局中渲染模板?
【发布时间】:2009-08-15 23:03:24
【问题描述】:

我正在尝试在液体布局中呈现液体模板(液体模板语言,而不是 CSS 液体布局的东西)。我似乎无法让布局部分呈现。目前使用:

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”替换为呈现的模板)

【问题讨论】:

    标签: ruby-on-rails liquid


    【解决方案1】:

    只是为了让其他人知道谁遇到了这个问题,上面发布的代码确实有效,问题在于名为 @template 的变量。我将@template 和@layout 重命名为@_tempalte 和@_layout,一切都按预期工作。

    【讨论】:

    • 是的,但是您从上面的代码中放弃的 rails 继承的模板查找和其他好东西会被劫持。虽然它有效,但在样式或功能上并不完全是“rails-ish”。
    【解决方案2】:

    对于在 ruby​​ on rails(尤其是 rails 3)中使用液体 - 我相信渲染液体模板的正确方法(并保持所有工作 rails 正在为您做的)如下......

    liquid gem 本身为rails 提供了一个liquid_view,因此您可以在调用#render 时连接rails 以查找“liquid”模板。此liquid_view 仅适用于rails 2.3 但可以通过以下更新轻松更新以使用 rails 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)
    

    可以在这里看到 --> https://github.com/danshultz/liquid/commit/e27b5fcd174f4b3916a73b9866e44ac0a012b182

    然后要正确渲染您的液体视图,只需调用

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

    在我们的应用程序中,由于我们有一些常见的液体属性,我们已经覆盖了基础控制器中的“渲染”方法,通过引用 #liquid_view_assigns 自动包含默认本地变量,该函数会为渲染调用额外添加液滴

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      • 1970-01-01
      • 1970-01-01
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多