1

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

为了提高效率,我使用了集合选项来呈现模板(请参阅下面的源代码)。但是当我尝试运行该任务时,我总是会收到以下错误消息:

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>

什么导致语法错误?

4

1 回答 1

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

于 2012-12-26T17:46:08.300 回答