Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check template file exists? #44

Closed
fangyuan opened this issue Dec 1, 2014 · 3 comments
Closed

Check template file exists? #44

fangyuan opened this issue Dec 1, 2014 · 3 comments

Comments

@fangyuan
Copy link

fangyuan commented Dec 1, 2014

Hi, I have a problem that how to detect template file whether exists before render it.
In my Dancer app route service, like this:

get '/help/:subject' => { my $subject = param 'subject'; template sprintf('help/%s.tt', $subject); # will get 500 if cannot found template }

So, it could check template file exists before render it and avoid error 500. But I didnot find answer in template manual.
Any ideas? Thanks.

@lejeunerenard
Copy link
Contributor

@fangyuan you can get the file path using Dancer's config sub to get the path to the views directory ( via config->{views} ) and concatenate the subject file name to that. With that file path you can check if the file exists using the build in -f perl file test function.

So all together your route would look like this:

get '/help/:subject' => {
  my $subject = param 'subject';
  my $tmpl = sprintf('help/%s.tt', $subject);
  if ( -f config->{ 'views' }.'/'.$tmpl ) {
    template $tmpl;
  } else {
    # Do something else instead of a 500
  }
}

@fangyuan
Copy link
Author

fangyuan commented Jan 7, 2015

@lejeunerenard, thanks for the suggestion, it is one both simple and quick solution.

There is another method, check template render result. If Dancer::Response returned, catch the error.

 my $response = template 'help/' . $subject;
 if (ref $response) { # Dancer::Response error
       if ($response->status == 500) {

       }
       #.....
       # normal output
       $response->status(200);
       return $response;
 }
 else { # normal output
        $response;
  }

@toddr
Copy link
Collaborator

toddr commented Oct 5, 2018

Closing as answered query.

@toddr toddr closed this as completed Oct 5, 2018
@toddr toddr added the Query label Oct 5, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants