Smarty PHP Template Tag


Using Smarty {php}{/php} Tags

Smarty templating with PHP gives you more than one file for which you can add PHP code. The first, and obvious choice is to use code raw PHP code directly into the '.php' file. However, you can code PHP into the template's partnering '.tpl' file.

Since Smarty 3.1, you must instantiate an instance of the SmartyBC class in order to be able to code PHP in the '.tpl' file using the tags {php}{/php}. Essentially, your main file with the '.php' will now have similar coding at the top of the file. The example snippet below shows that you will use the SmartyBC class instead of the default smarty class.

If you have done enough research, you may have read that it is not recommended to use {php}{/php} tags with the '.tpl' file since the front end coder can now use them. In fact, it seems to defeat the purpose of using Smarty to begin with, which is to separate PHP coding from the design code.

.php File

 //include_once("libs/smarty.class.php"); //$smarty = new smarty();  // allow php tags in the tpl file require_once('libs/SmartyBC.class.php'); $smarty = new SmartyBC(); 

.tpl File

Now that you can use the {php}{/php} tags in the ".tpl" file, here is an example that prints "Hello World".

 {php} echo "Hello World"; {/php}