[dancer-users] TT 'include file if exists'

Lennart Hengstmengel lennart at farenji.net
Mon May 1 09:55:03 BST 2017


Hi Nathan,

One way to accomplish what you want is to write your own 
Template::Provider subclass. You'll need to override at least the 
_template_content($path) method and there you can implement the logic 
you need, like returning a (pre defined) content if $path does not exist.

my $provider = My::TT::Provider->new();
my $tt = Template->new({
     ENCODING       => "utf8",
     LOAD_TEMPLATES => [ $provider ],
});
$tt->process( ... );

See: 
http://www.template-toolkit.org/docs/modules/Template/Provider.html#section_SUBCLASSING 


Hope this helps!

Best regards,
Lennart



On 01-05-17 07:58, Nathan Bailey wrote:
> Hi all,
>  More of a Template Toolkit question rather than Dancer per se, but is 
> there a better way to load a file only if it exists?
>
> From my Googling around, it appears the only approaches are (a) 
> Try/Catch in TT or (b) include a full <%PERL%> call (which I'm 
> guessing may be a little heavy to do on every page load).
>
> I'd like to dynamically include a help file if it exists, otherwise 
> provide a 'No help available for this page' message. Current code 
> looks like this:
> <% help_file = 'help' _ request.request_uri.remove('\?.*') _ '.tt' %>
> <% TRY %>
>    <% USE File('/full_unix_path/views/' _ help_file) %>
>    <% INCLUDE $help_file %>
> <% CATCH File %>
>    '<% help_file %>' doesn't exist: <% error.info <http://error.info> %>
> <% END %>
>
> I'm not keen on the fixed path and it seems overkill to have to 
> try/catch if the file exists rather than just load it (and fail 
> silently) or test if it exists and then load.
>
> Do people have better patterns for managing inline help?
>
> thanks,
> Nathan
>
>
> _______________________________________________
> dancer-users mailing list
> dancer-users at dancer.pm
> http://lists.preshweb.co.uk/mailman/listinfo/dancer-users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.preshweb.co.uk/pipermail/dancer-users/attachments/20170501/bc620239/attachment.html>


More information about the dancer-users mailing list