【问题标题】:Passing options to template function in thor将选项传递给 thor 中的模板函数
【发布时间】:2011-06-27 19:43:00
【问题描述】:

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

我偶然发现了捆绑器 cli 源,其中使用了 thors 模板操作,如下所示:

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)

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

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

【问题讨论】:

  • 您在 Thor 文件中尝试的哪些代码不起作用?
  • 我确实复制了上面的代码,但它没有捕捉到传递的选项。

标签: ruby templates erb thor


【解决方案1】:

通过使用实例变量,它应该可以工作。

@name = name
template("source","target")

我的模板如下所示:

<test><%= @name %></test>

这对我有用。我还没有尝试过传递特定值。

【讨论】:

    【解决方案2】:

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

    Author email: <%= config[:author_email] %>
    

    有效。

    【讨论】:

    • 这对我也有用。传递给templateopts 的哈希值在Erb 模板中称为config
    猜你喜欢
    • 2017-12-25
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多