我在erb模板中有下一个代码:
<% if @proxy_cache_path.is_a?(Hash) -%>
<% @proxy_cache_path.sort_by{|k,v| k}.each do |key,value| -%>
proxy_cache_path <%= key %> keys_zone=<%= value %> levels=<%= @proxy_cache_levels %> max_size=<%= @proxy_cache_max_size %> inactive=<%= @proxy_cache_inactive -%>
<% end -%>如何将其移植到epp模板?我发现它的信息很低。请帮帮忙。
发布于 2017-07-29 12:04:51
以下是你如何做到的:
显示示例类以及如何声明ERB和EPP模板以进行比较:
# manifests/init.pp
class foo () {
$proxy_cache_path = {
'apples' => 1,
'bananas' => 2,
}
$proxy_cache_levels = 2
$proxy_cache_max_size = 2
$proxy_cache_inactive = 2
# Showing use of ERB:
file { '/foo':
ensure => file,
content => template('foo/mytemplate.erb')
}
# Showing use of EPP, which requires an explicit parameters hash:
file { '/bar':
ensure => file,
content => epp('foo/mytemplate.epp', {
'proxy_cache_path' => $proxy_cache_path,
'proxy_cache_levels' => $proxy_cache_levels,
'proxy_cache_max_size' => $proxy_cache_max_size,
'proxy_cache_inactive' => $proxy_cache_inactive,
}),
}
}更正*供比较的雇员再培训局档案的内容:
# templates/mytemplate.erb
<% if @proxy_cache_path.is_a?(Hash) -%>
<% @proxy_cache_path.sort_by{|k,v| k}.each do |key,value| -%>
proxy_cache_path <%= key %> keys_zone=<%= value %> levels=<%= @proxy_cache_levels %> max_size=<%= @proxy_cache_max_size %> inactive=<%= @proxy_cache_inactive -%>
<% end -%>
<% end -%>(*问题中的代码缺少关闭的end。)
EPP文件的内容:
# templates/mytemplate.epp
<%- | Hash[String, Integer] $proxy_cache_path, Integer $proxy_cache_levels, Integer $proxy_cache_max_size, Integer $proxy_cache_inactive | -%>
<% include stdlib -%>
<% $proxy_cache_path.keys.sort.each |$key| { -%>
proxy_cache_path <%= $key %> keys_zone=<%= $proxy_cache_path[$key] %> levels=<%= $proxy_cache_levels %> max_size=<%= $proxy_cache_max_size %> inactive=<%= $proxy_cache_inactive -%>
<% } -%>有关EPP模板文件内容的注意事项:
1)参数及其类型定义在模板的第一行。使用这一行是可选的,但很好的做法。
2)由于我们在第一行中声明了类型,因此测试$proxy_cache_path是否是Hash是不必要的,也是多余的。
3)为了访问keys和sort函数,需要包含stdlib。这与Ruby (ERB)不同,在那里这些方法是内置到语言中的。
4)我简化了相对于Ruby ( ERB )的代码,因为木偶没有sort_by函数,而且实际上也没有必要在ERB中使用它,它可以重写为:
<% if @proxy_cache_path.is_a?(Hash) -%>
<% @proxy_cache_path.sort.each do |key,value| -%>
proxy_cache_path <%= key %> keys_zone=<%= value %> levels=<%= @proxy_cache_levels %> max_size=<%= @proxy_cache_max_size %> inactive=<%= @proxy_cache_inactive -%>
<% end -%>
<% end -%>最后,进行一些测试:
# spec/classes/test_spec.rb:
require 'spec_helper'
describe 'foo', :type => :class do
it 'content in foo should be the same as in bar' do
foo = catalogue.resource('file', '/foo').send(:parameters)[:content]
bar = catalogue.resource('file', '/bar').send(:parameters)[:content]
expect(foo).to eq bar
end
end考试就通过了。
见docs 这里。
https://stackoverflow.com/questions/45387586
复制相似问题