PHPにSmartyをセットアップ

PHPにSmartyをセットアップ

2019-01-264 min read

目次

  1. 概要
  2. 試した環境
  3. smartyについて
  4. ダウンロード
  5. smartyの配置
  6. smarty呼び出し

概要

PHPにSmartyをセットアップをするメモ

試した環境

PHP 7.1.19 Smarty 3.1.33

Smartyについて

https://www.smarty.net/

古くからあるPHPのテンプレートエンジンです。

Smarty と twig のトレンド比較

PHPのテンプレートエンジンとして有名なSmartyですが、最近はbaldeやtwigという名前もよく見かけるようになりました。

ダウンロード

Smartyの最新版はGitHubからzipかtarで落としてきます。

https://github.com/smarty-php/smarty/releases

smartyの配置

落として解凍したsmartyディレクトリを任意の場所に配置します。 実装するときに絶対パスで参照するのであれば、どの場所でも問題ないとは思いますが、 include_pathで設定されている場所に配置するのがベターだと思います。

Smarty呼び出し

index.php

include_once("smarty-3.1.33/libs/Smarty.class.php");

// smartyオブジェクト生成
$smarty = new Smarty();

// 設定
$smarty->template_dir = "/path/to/template/"; //相対パスでも可
$smarty->compile_dir = "/path/to/cache/"; //相対パスでも可

// 変数をセット
$smarty->assign("test", "Hello World!");

// テンプレートを読み込んでレンダリング
$smarty->display('index.tpl');

index.tpl

<!DOCTYPE>
<html>
<head>
</head>
<body>
{$test}
</body>
</html>

Macであればターミナルから

php -S localhost:3333 index.php

を実行し、「Hello World!」と表示されていれば成功です。

Author
githubzennqiita
ただの備忘録です。

※外部送信に関する公表事項