Search code examples
template-toolkitdancer

Is there a way to bind variables to a template toolkit template?


I have an array which I pass to a TT file that's used to populate the navbar.

I'm using a main template as a base and sub templates for the body content.

I wanted to know if it's possible to declare that 'the main template should always receive this array', instead of having to pass this array along every time I load a view (oh yeah, I'm using Dancer btw :P), ex:

get '/' => sub {
    template 'index', { for_all_i_know => $this_never_changes }
}

get '/about' => sub {
    template 'about', { for_all_i_know => $this_never_changes }
}

instead of doing that, is there a way I can clean it up? something like:

bind template 'main' { for_all_i_know => $this_never_changes };

that way I can just do:

get '/' => sub {
    template 'index';
}

and the main template will still load the variable 'for_all_i_know'


Solution

  • Yup you want to declare those variables in a hook. For example in your main class:

    hook 'before_template_render' => sub {
    
      var helpdesk => 'help@example.com';
    
    };
    

    Then in your view or layout templates you can access those like this:

    <p> For assistance please contact us at <% vars.helpdesk %>. 
    

    ... without having to explicitly pass it in.