PHP: How to use Smarty

Aug 29, 2020 PHP Smarty

This is the method confirmed on Ubuntu 20.04.

Download library

wget https://github.com/smarty-php/smarty/archive/v3.1.35.tar.gz

Install

Unzip >v3.1.35.tar.gz and put it under /usr/local/lib

Sample program

Folder structure

$ tree
.
├── templates
│  └── hello.tpl
├── templates_c
└── test.php

Put it so that it can be written with templates_c. With 777, you can write securely.

<?php
define('SMARTY_DIR','/usr/local/lib/smarty-3.1.35/libs/');
require_once(SMARTY_DIR .'Smarty.class.php');

 
$smarty = new Smarty();
 
$smarty->template_dir = "./templates/";
$smarty->compile_dir = "./templates_c/";

$name = $_GET['name'];
 
$smarty->assign("name", $name);

$smarty->display("hello.tpl");
?>
<!DOCTYPE html>
<html lang="ja">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hello World!</title>
</head>
<body>
This page is a Template. <p />
<blockquote>
<H2> Hello {$ name}! </ H2>
</blockquote>
<p />
<hr />
Aug/29/2020 PM 13:22<p />
</body>
</html>

Execution result

test.php?name=Nankichi Niimi

smarty_aa.png

test.php?name=Kenji Miyazawa

smarty_bb.png