Tuesday, July 21, 2009

How to include a php file inside smarty template

Well, many one of you heard about smarty template. In simple way we can say, Smarty template makes your PHP scripts independent of the layout.

While working with smarty template you may need to run a php code from the smarty template. Smarty always give the flexibility to do display code simply as a text as well as to execute php code.

Let's assume we have just installed smarty.
-You will see under Smarty>libs folder the main smarty class php file named Smarty.class.php and we need to make instance of Smarty class to use it.

-You can see sample code under Smarty>demo.

-And the template resides under Smarty>demo>templates.

Now we will execute php script named welcome.php from template named welcome.tpl

My welcome.php contains,
<?php
echo "Welcome to arjudba world.";
?>


and is saved under Smarty>demo.

My welcome.tpl contains,
{include_php file="welcome.php"}

and is saved under Smarty>demo>temaplates. Note that we can give full path here. Like {include file="include($_SERVER['DOCUMENT_ROOT'].'/includes/welcome.php');"}

Now from a php file we need to call the template file welcome.tpl and eventually template file will call welcome.php file. Let's name this php file as Smarty/display.php which contains,

<?php

require '../libs/Smarty.class.php';

$smarty = new Smarty;

$smarty->compile_check = true;
$smarty->debugging = true;
$smarty->display('welcome.tpl');

?>



Now in browser if you run for example on machine http://localhost/smarty/demo/display.php it will display,
Welcome to arjudba world.

And you are done. From welcome.tpl you ran welcome.php script.

I have shown a simple way above about how to run php script from template. There are other ways to do the job. Like in the template file writing as,

{php}
include("welcome.php");
{/php}


Related Documents
Datatypes in Php
Integer and floating point number in Php
Variables in PHP
Magic constants in php
Boolean datatype in Php

No comments:

Post a Comment