Using Angular JS With Smarty Templates

Smarty Templates and Angular JS

Angular JS is a Javascript framework that fits in well with Smarty templates. To use the Angular JS framework, all you need to is alter the <html> tag tag to <html ng-app>, add the script angular.min.js into the head and add ng-model tags to your form elements. 

To use Angular JS with Smarty has a little twist from a basic html page. You will use literal tags around the angular js tags which look like {{ng-model value goes here}}. So, with the example below, an html file would write the output of the first name by using  {{first_name}} while Smarty will look like {literal}{{first_name}}{/literal}. A you can see, the tags for Angular JS are very similar to Smarty which makes them very easy to use with Smarty templates.

The example below will show the complete usage.

.php File

<?php
if (count($_POST) > 0) {
// die("Works");
    print_r($_POST);
    echo $_POST['first_name'] . " - " . $_POST['last_name'];
}

include("libs/smarty.class.php");
$smarty = new Smarty ();

$smarty->display("includes/header.inc.tpl"); //compile and display output
$smarty->display("angular.tpl"); //compile and display output
$smarty->display("includes/footer.inc.tpl"); //compile and display output
?>

.tpl File

<!doctype html>
<html ng-app>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.15/angular.min.js"></script>
</head>
<body>
<div>
    <form name="job_form" method="post" action="{$smarty.server.PHP_SELF}">
        <p>First Name:</p>
        <input type="text" ng-model="first_name" name="first_name" placeholder="">

        <p>Last Name:</p>
        <input type="text" ng-model="last_name" name="last_name" placeholder="Last Name Here">
        <input type="submit" name="submit" value="Submit"/>
    </form>
    <hr>
    <h2>Direct output:</h2>

    <p>My name is {literal}{{first_name}}{/literal} {literal}{{last_name}}{/literal}!</p>
</div>
</body>
</html>

Browser Output

Add Content HereAdd Header Code Here

First Name:

Last Name:

  Submit 


Direct output:

My name is John Smith!

Add Custom Footer