简体   繁体   中英

Rails render causes syntax error undefined local variable or method `name'

I am writing a rake task that reads all names of all chancellors in the database and try to pass this values to a HAML template.

To make it more efficient I used the collection option to render the template(see below in the source code). But when I try to run that task I get always this error message:

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

Here is the task code for this problem:

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

And here is the haml template which should be filled:

%firstname #{name}

I want to get an output like:

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

I tried even to put name as a instance variable in the template, so that it looks like this:

%firstname #{@name}

But then the value of firstname is empty and I get this line as output:

<firstname></firstname>

What causes the syntax error?

There is a Syntax error in this line:

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

Change it to:

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

Go to this URL to see what kind of parameters you can pass into the render function. http://apidock.com/rails/ActionController/Base/render

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM