How to access variables in an erb-subtemplate in puppet?

example.pp

$foo = 'bar'$content = template('mymodule/maintemplate.erb')


maintemplate.erb

<% bar = foo + "extra" %>

foobar = scope_function_template(['mymodule/subtemplate.erb'])


subtemplate.erb

<%# here i want to access the variable bar %>
<%= bar %>


there is the function

<%= scope.lookupvar('::bar') %>


is there a kind of parent::bar in erb templateing, or can i pass some variables to the subtemplate, or can i only access the outer variable (of the .pp file) with ::foo

-
–  rbtux Nov 20 '12 at 22:21
@rbtux thank you very much. can you add it as answer so that i can accept it? –  c33s Nov 21 '12 at 10:59

As stated in this bugreport/feature request: http://projects.puppetlabs.com/issues/6492 there is a workaround using scope.setvar

<% bar = foo + "extra" %>
scope.unsetvar('bar')
scope.setvar('bar',bar)


This is ugly but seems to work...

-
scope.unsetvar() was removed in github.com/puppetlabs/puppet/commit/… and is not available in puppet 3.x –  jonhattan Apr 3 '13 at 12:45

So I read at http://projects.puppetlabs.com/issues/6592#note-6 that a TemplateWrapper could be used and I end up with this snippet:

<%
newscope = scope.compiler.newscope(scope)
newscope.setvar(k, v)
wrapper = Puppet::Parser::TemplateWrapper.new(newscope)
wrapper.file = 'templatefile.erb'
%>
<%= wrapper.result %>

-