根据条件渲染部分

时间:2014-08-30 17:11:08

标签: ruby-on-rails

您好我想根据条件呈现模板,但是我收到了丢失的模板错误:

Missing partial template/default_template with {:locale=>[:es], :formats=>[:html], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee]}. Searched in:

方式:

module ApplicationHelper
  def select_template_for(analysis)
     special_templates = %w(cat dog)
     selected_template = special_templates.find { |tpl| tpl == analysis } || 'default_template'
     puts selected_template
     render "template/#{selected_template}"
   end  
end

查看:

<%= select_template_for(@result.id_analysis) %>

文件夹结构:

pets
  show (where the helper is called)
  template
     _cat.html.erb
     _dog.html.erb
     _default_template.html.erb

2 个答案:

答案 0 :(得分:2)

您可以尝试render "pets/template/<template_name>"

示例:

def render_template_for(type)
  partials = %w(cat dog)
  partial = partials.include?(type) ? type : 'default_template'

  render "pets/template/#{partial}"
end

甚至:

def render_template_for(type)
  partial = %w(cat dog) & [type]
  render "pets/template/#{partial[0] || 'default_template'}"
end

def render_template_for(type)
  partial = %w(cat dog).delete type
  render "pets/template/#{partial || 'default_template'}"
end

答案 1 :(得分:1)

根据ISO4的答案,根据您的方法名称,将您的render语句从帮助方法移出view

方式:

module ApplicationHelper
  def select_template_for(analysis)
     special_templates = %w(cat dog)
     special_templates.find { |tpl| tpl == analysis } || 'default_template'
  end  
end

查看:

render "pets/template/#{select_template_for(@result.id_analysis)}"