繁体   English   中英

Rails渲染导致语法错误未定义的局部变量或方法“名称”

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

我正在编写一个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>

是什么导致语法错误?

此行中有一个语法错误:

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

更改为:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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