As far as I can see from the TT2 docs, there is no native way to do this:

if (template address exists) { include template } else { include other template }

or more succinctly:

[% INCLUDE 'my/best/choice' || 'my/other/option' %]

Which seems a great shame, especially as TT croaks when a template component is missing. It would allow all sorts of useful structures, most obviously the chance to default to a generic component if no more specific version is available.

It's quite easy to implement from the outside, provided you still have the template path:

sub template_exists { my ($self, $file) = @_; my $path = $self->config->template_path; return 1 if grep { -e && -f && -r } map { "$_/$file" } @$path; return; }

But it isn't easy to make that look friendly in the templates, which I don't like (and which generates support work, which I also don't like :)

[% FOREACH thing = collection %] [% template = factory.template_exists("list/types/${thing.type}.ht +ml") ? "list/types/${thing.type}.html" : "list/types/default.html" %] [% INCLUDE $template %] [% END %]

So I mostly confine this to the darker corners of the template hierarchy. I'd like to use it more widely, and I can't be alone in that, which makes me think there's an odd bit of syntax or a clever trick that I've missed, and everything could look nice again. Can anyone advise, please, or suggest another approach?

Thanks,
Will


In reply to testing for the existence of a tt template: better way? by thpfft

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.