Search code examples
phpsmartymultilinestring

Chaining smarty templates and clean multiline strings - PHP


I know that the first part of this is subjective, but I'd like to hear some different techniques people use. This is a two part question: what do you use for complex multiline strings in PHP? And, can I use a composition type of relationship with smarty?

Question 1: I know there is heredoc and the "." operator. I'm looking for fresh, more readable ideas if there are any.

Question 2: To be more specific, here is what I would like to do with smarty.

Say I have a template, base.tpl:

<html>
<head><title></title></head>
<body>
{$main_content}
</body>
</html>

Can I chain templates, i.e. another template that represents $main_content, say main.tpl:

<div id="header">$header</div>
<div id="container">
<h1>{$first_header}</h1>
<p>{$first_paragraph}</p>
<h1>{$second_header}</h1>
<p>{$second_paragraph}</p>

I want in whatever.php to load one template into the other, so i.e.:

// ... including smarty and all other boiler plate things ...

$smarty -> assign('first_header', "Foo");
$smarty -> assign('first_paragraph', "This is a paragraph");
$smarty -> assign('second_header', "Bar");
$smarty -> assign('second_paragraph', "This is another paragraph");

$main_content = $smarty->load('main.tpl');
$smarty -> display('base.tpl');

I know that there is "template inheritance" in smarty, but I'm not familiar with it. Can it give me similar functionality to this?

Note: I think my biggest problem with heredoc is that I can't get syntax highlighting for html (if i specify html in the heredoc string). Without the highlighting, the html that I want to pass through smarty is much harder to read, which kind of defeats the purpose of smarty.


Solution

  • You'll want to use {include} to call templates (fragments) within a template.

    http://www.smarty.net/docsv2/en/language.function.include.tpl

    <html>
    <head>
      <title>{$title}</title>
    </head>
    <body>
    {include file='page_header.tpl'}
    
    {* body of template goes here, the $tpl_name variable
       is replaced with a value eg 'contact.tpl'
    *}
    {include file="$tpl_name.tpl"}
    
    {include file='page_footer.tpl'}
    </body>
    </html>
    

    Passing variables into included templates:

    {include file='links.tpl' title='Newest links' links=$link_array}
    {* body of template goes here *}
    {include file='footer.tpl' foo='bar'}
    

    In terms of multi-line strings, I tend to use this pattern:

    $my_string = "Wow, this is going to be a long string. How about "
               . "we break this up into multiple lines? "
               . "Maybe add a third line?";
    

    As you said, it's subjective. Whatever you feel comfortable with and as long as its easily readable...