Rails渲染导致语法错误未定义局部变量或方法`name'

时间:2012-12-26 16:38:42

标签: ruby-on-rails rake haml render

我正在编写一个rake任务,它读取数据库中所有大臣的所有名称,并尝试将此值传递给HAML模板。

为了提高效率,我使用了collection选项来渲染模板(参见下面的源代码)。但是当我尝试运行该任务时,我总会得到以下错误消息:

undefined local variable or method `name' for #<Template:0x007f9094286078>

以下是此问题的任务代码:

task :template => :environment do

  #this class is responsible for rendering templates in a rake task  
  class Template < ActionView::Base
    include Rails.application.routes.url_helpers
    include ActionView::Helpers::TagHelper

    def default_url_options
      {host: 'yourhost.org'}
    end
  end

  firstNames = Array.new

  #stores the first names of all chancellors in an array
  for chans in Chancellor.all
    firstNames.push(chans.first_name)
  end

  #sets the path to the template
  template = Template.new(Rails.root.join('lib','tasks'))

  #trying to render the template with a collection
  finalString = template.render(:template => "_chancellor.xml.haml", 
      :collection => firstNames, :as => :name)

  puts finalString
end

这是应该填充的haml模板:

%firstname #{name}

我希望获得如下输出:

<firstname>someName1</firstname>
<firstname>someName2</firstname>
<firstname>someName3</firstname> ....

我甚至尝试将name作为实例变量放在模板中,所以它看起来像这样:

%firstname #{@name}

但是,firstname的值为空,我将此行作为输出:

<firstname></firstname>

导致语法错误的原因是什么?

1 个答案:

答案 0 :(得分:0)

此行中存在语法错误:

finalString = 
    template.render(:template => "_chancellor.xml.haml", 
    :collection => firstNames, :as => :name)

将其更改为:

finalString = 
    template.render(:partial => "chancellor", collection => firstNames, :as => :name)

转到此URL以查看可以传递到渲染功能的参数类型。 http://apidock.com/rails/ActionController/Base/render