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

D Perrett perrettdl at googlemail.com
Mon May 1 10:24:49 BST 2017


Running TT in Dancer, you can pass any variable into TT, including a
coderef. If you pass in, e.g. { file_exists => sub { -f $_[0] } },
then your TT code can begin

<% IF file_exists(help_file) %>...

Daniel

On 1 May 2017 at 06:58, Nathan Bailey <web at polynate.net> 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 %>
> <% 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
>


More information about the dancer-users mailing list