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. You can also set the $compile_id variable once instead of passing this to each call to this function.

Example 14.21. fetch()

$smarty = new Smarty;


// set a separate cache_id for each unique URL
$cache_id = md5($_SERVER['REQUEST_URI']);

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

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


Example 14.22. Using fetch() to send an email

The email_body.tpl template

Dear {$},

Welcome and thank you for signing up as a member of our user group.

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


List master

{textformat wrap=40}
This is some long-winded disclaimer text that would automatically get wrapped
at 40 characters. This helps make the text easier to read in mail programs that
do not wrap sentences for you.


The php script using the PHP mail() function


// get $contact_info from db or other resource here


mail($contact_info['email'], 'Thank You', $smarty->fetch('email_body.tpl'));



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