我正在编写一个 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>
什么导致语法错误?