1

データベース内のすべてのチャンセラーのすべての名前を読み取り、この値を HAML テンプレートに渡そうとする rake タスクを作成しています。

より効率的にするために、コレクション オプションを使用してテンプレートをレンダリングしました (以下のソース コードを参照)。しかし、そのタスクを実行しようとすると、常に次のエラー メッセージが表示されます。

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> ....

次のようになるように、名前をインスタンス変数としてテンプレートに入れてみました。

%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 に答える