将选项传递给模板函数

dev*_*boy 9 ruby templates erb thor

我正在寻找一种方法来在thors模板操作中将选项传递给ERB模板引擎.

我偶然发现了使用thors模板操作的bundler cli源代码,如下所示:

opts = {:name => name, 
    :constant_name => constant_name, 
    :constant_array => constant_array, 
    :author_name => author_name, 
    :author_email => author_email
}

template(File.join("newgem/Gemfile.tt"),
           File.join(target, "Gemfile"),
            opts)
Run Code Online (Sandbox Code Playgroud)

但是当我在我的Thor任务中添加这样的选项时,ERB找不到它们,我只能在我的thor类中使用参数和函数来在模板中设置变量.

我不知道ruby中的绑定是如何工作的,也许有一种方法可以通过绑定到ERB来传递范围.

Dr.*_*rer 13

通过使用实例变量,它应该工作.

@name = name
template("source","target")
Run Code Online (Sandbox Code Playgroud)

我的模板看起来像这样:

<test><%= @name %></test>
Run Code Online (Sandbox Code Playgroud)

这适合我.我没有尝试传递具体的值.


小智 12

我找不到任何文档来回答这个问题,但是阅读Bundler CLI的来源,看来如果你试图在模板中引用:author_email参数,

Author email: <%= config[:author_email] %>
Run Code Online (Sandbox Code Playgroud)

作品.

  • 这对我也有用.传递给`template`的`opts`的哈希在Erb模板中称为`config`. (2认同)