Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- $template = new template(array(
- 'all_head.twig', 'page.twig', 'all_foot.twig'),
- 'template/', '/tmp');
- $template->addJS('script.js'); # Also Takes arrays();
- $template->addCSS('style.css'); # Also Takes arrays();
- $template->title = 'Test Template and Twig';
- echo $template;
- all_head.twig
- ...
- <title>{{ title }}</title>
- <!-- Start JS -->
- {% for js in javascript %}
- <script type="text/javascipt" src="{{ js }}"></script>
- {% endof %}
- <!-- End JS -->
- ...
- */
- class template {
- var $rendered = false;
- var $twig = null;
- var $pages = array();
- var $data = array();
- function __construct($pages, $path, $cache=false) {
- // Save the pages
- if (!is_array($pages)) $pages = array($pages);
- $this->pages = $pages;
- // Check that the pages are real
- foreach ($this->pages as $page) {
- if (!is_file($path.'/'.$page)) {
- die("Template file <em>$page</em> not found");
- }
- }
- // Load Twig
- require_once "Twig/lib/Twig/Autoloader.php";
- Twig_Autoloader::register();
- $twigLoader = new Twig_Loader_Filesystem($path);
- $this->twig = new Twig_Environment($twigLoader, array(
- 'cache' => $cache,
- ));
- // Set up data
- $this->data = array(
- 'javascript' => array(),
- 'css' => array(),
- );
- }
- function render($return=false) {
- if (!$this->rendered) {
- if ($return) {
- $ret = '';
- foreach ($this->pages as $page) {
- $ret .= $this->twig->render($page, $this->data);
- }
- } else {
- $ret = true;
- foreach ($this->pages as $page) {
- echo $this->twig->render($page, $this->data);
- }
- }
- $this->rendered = true;
- return $ret;
- } else {
- return false;
- }
- }
- function __toString() {
- return $this->render(true);
- }
- function addJavascript($path) {
- if (is_array($path)) {
- $this->data['javascript'] = array_merge($this->data['javascript'], $path);
- } else {
- $this->data['javascript'][] = $path;
- }
- }
- function addJS($path) {
- $this->addJavascript($path);
- }
- function addCSS($path) {
- if (is_array($path)) {
- $this->data['css'] = array_merge($this->data['css'], $path);
- } else {
- $this->data['css'][] = $path;
- }
- }
- function __set($key, $val) {
- $this->data[$key] = $val;
- }
- function __get($key) {
- echo "get $key";
- return $this->data[$key] = $val;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement