Get Smarty



Smarty Icon

You may use the Smarty logo according to the trademark notice.

Smarty Template Engine Smarty Template Engine

For sponsorship, advertising, news or other inquiries, contact us at:

Sites Using Smarty



fetch() — returns the template output


string fetch(string template,
             string cache_id,
             string $compile_id);

This returns the template output instead of displaying it. Supply a valid template resource type and path. As an optional second parameter, you can pass a $cache id, see the caching section for more information.

As an optional third parameter, you can pass a $compile_id. This is in the event that you want to compile different versions of the same template, such as having separate templates compiled for different languages. Another use for $compile_id is when you use more than one $template_dir but only one $compile_dir. Set a separate $compile_id for each $template_dir, otherwise templates of the same name will overwrite each other. You can also set the $compile_id variable once instead of passing this to each call to this function.

Example 13.14. fetch()

$smarty = new Smarty;

$smarty->caching = true;

// only do db calls if cache doesn't exist
if(!$smarty->is_cached('index.tpl')) {

  // dummy up some data
  $address = '245 N 50th';
  $db_data = array(
               'City' => 'Lincoln',
               'State' => 'Nebraska',
               'Zip' => '68502'



// capture the output
$output = $smarty->fetch('index.tpl');

// do something with $output here
echo $output;


Example 13.15. Using fetch() to send an email

The email_body.tpl template

Dear {$},

Welcome and thankyou for signing up as a member of our user group,

Click on the link below to login with your user name of '{$contact.login_id}'
so you can post in our forums.


List master
Some user group

{include file='email_disclaimer.tpl'}


The email_disclaimer.tpl template which uses the {textformat} modifier.

{textformat wrap=40}
Unless you are named "{$}", you may read only the "odd numbered
words" (every other word beginning with the first) of the message above. If you have
violated that, then you hereby owe the sender 10 GBP for each even
numbered word you have read


The php script using the PHP mail() function


// get contact from database eg using pear or adodb
$query  = 'select name, email, login_id from contacts where contact_id='.$contact_id;
$contact = $db->getRow($sql);
$smarty->assign('contact', $contact);

mail($contact['email'], 'Subject', $smarty->fetch('email_body.tpl'));



See also {fetch} display(), {eval}, and template_exists().

by Marc on Oct 25, 2011 at 8:27
Shouldnt this: $contact = $db->getRow($sql); be: $contact = $db->getRow($query);


Sponsors [info]