Sunday Apr 18, 2010  0

Loading Smarty templates form a db

In my recent project which required an interface for the users to edit the templates. I was faced with the challenge of storing the smarty templates used by the site into a database. Then loading thems for either editing by the user or to be parsed and displayed.

To accomplish this I used the register_resource() functionality of Smarty. Here are the functions I used, which can also be found in the manual which I modified a bit to suite my needs.

function db_get_template ($tpl_name, &$tpl_source, &$smarty_obj) {
	//get the template from the database
	$q = mysql_query("SELECT template_data FROM template_table WHERE template_name = '$tpl_name'");
	if (mysql_num_rows($q)) {
		$tpl_source = stripslashes(mysql_result($q,0,"template_data"));
		mysql_free_result($q);
		return true;
	} else {
		return false;
	}
}
function db_get_timestamp($tpl_name, &$tpl_timestamp, &$smarty_obj)  {
	//get the timestamp of the template
	//you can either get it form your db you just set the current time.
	$tpl_timestamp = strtotime("now");
	return true;
} 

function db_get_secure($tpl_name, &$smarty_obj)  {
	// assume all templates are secure
	return true;
}
function db_get_trusted($tpl_name, &$smarty_obj)  {
	// not used for templates
}

//register the resource
$tpl->register_resource("db", array("db_get_template",
							"db_get_timestamp",
							"db_get_secure",
							"db_get_trusted"));

We will only be using the db_get_template() function, the other 3 functions are required by Smarty. There are 2 ways I used this function.

First is I load the template in a variable and assign it to a variable:

	$template_name = "TEMPLATE NAME HERE";
	$content = $smarty->fetch("db:{$template_name}");
	$smarty->assign('content', $content);

Second is to display the template right away:

	$smarty->display("db:{$template_name}");

To summarize the argument for $smarty->display(“db:{$template_name}”);db‘ is the name of the resource we registered earlier. while the $template_name is a variable holding the template name I want to search. In essence this just calls the db_get_template() function we made earlier.

  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • Technorati
  • Twitter

Leave a Comment

Previous post:

Next post: