Skip to content

Instantly share code, notes, and snippets.

@royteusink
Last active February 20, 2019 10:09
Show Gist options
  • Save royteusink/9f848291bc313ff711fbed59b5e34a65 to your computer and use it in GitHub Desktop.
Save royteusink/9f848291bc313ff711fbed59b5e34a65 to your computer and use it in GitHub Desktop.
Add Smarty Template to Laravel 5

Add (latest) Smarty Template to Laravel 5.

composer require smarty/smarty --prefer-dist dev-master

.gitignore

/storage/smarty

config/app.php

Add to 'providers':

App\Providers\SmartyServiceProvider::class,

config/smarty.php

<?php

return [
	'extension' => 'tpl',
	'caching' => true,
	'cache_lifetime' => 120,
	'escape_html' => false,

	'template_path' => base_path('resources/views'),
	'cache_path' => storage_path('smarty/cache'),
	'compile_path' => storage_path('smarty/compile'),
	'plugins_path' => base_path('resources/smarty/plugins'),
	'config_path' => base_path('resources/smarty/config'),
];

App\Engines\SmartyEngine.php

<?php

namespace App\Engines;

use Illuminate\View;
use Illuminate\View\Engines;
use Illuminate\View\Compilers\CompilerInterface;
use Illuminate\Contracts\View\Engine;

use Smarty;

class SmartyEngine implements Engine {

	protected $config;

	public function __construct($config) {
		$this->config = $config;
	}

	public function get($path, array $data = []) {
		return $this->evaluatePath($path, $data);
	}

	protected function evaluatePath($path, $data) {
		$smarty = new Smarty();
		$smarty->setTemplateDir($this->config('template_path'));
		$smarty->setCompileDir($this->config('compile_path'));
		$smarty->setCacheDir($this->config('cache_path'));
		$smarty->setConfigDir($this->config('config_path'));
		$smarty->addPluginsDir($this->config('plugins_path'));

		$smarty->caching = $this->config('caching', true);
		$smarty->cache_lifetime = $this->config('cache_lifetime');
		$smarty->compile_check = true;
		$smarty->escape_html = $this->config('escape_html', false);

		foreach ($data as $var => $val) {
			$smarty->assign($var, $val);
		}

		return $smarty->fetch($path);
	}

	public function getCompiler() {
		return $this->compiler;
	}

	protected function config($key, $default = null) {
		return $this->config->get('smarty.' . $key, $default);
	}

}

App\Providers\SmartyServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Engines\SmartyEngine;

class SmartyServiceProvider extends ServiceProvider {

	public function register() {
	}
	
	public function boot() {
		$this->app['view']->addExtension($this->app['config']->get('smarty.extension', 'tpl'), 'smarty', function() {
			return new SmartyEngine($this->app['config']);
		});
	}

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment