Browse Source

* Add {#include path}

Nathaniel van Diepen 7 years ago
parent
commit
0c4bb89f93
1 changed files with 25 additions and 1 deletions
  1. 25 1
      Data/template.class.php

+ 25 - 1
Data/template.class.php

@@ -9,6 +9,7 @@
 		use Events;
 		private static $templates = [];
 		public static $cachedir;
+		public static $basedir = __DIR__;
 		private static $regex = [
 			'match'=>'/\{([^#\/][^}\n]+?)\}/i',
 			'each'=>'/\{#each ([^}]*)\}([\S\s]*)\{\/each\}/i',
@@ -19,7 +20,8 @@
 			'gettext'=>"/{_([^,}]+)(?:, ?([^},]+))*\}/i",
 			'gettext_string'=>'/^([\'"])(.+)\1$/i',
 			'echo'=>'/\{=([^}]+)\}/i',
-			'eval'=>'/\{\?([\W\w\S\s]+)\?\}/i'
+			'eval'=>'/\{\?([\W\w\S\s]+)\?\}/i',
+			'include'=>'/{#include ([^}]+)}/i'
 		];
 		private $template;
 		private $name;
@@ -73,6 +75,17 @@
 				$ignored[] = $matches[1];
 				return '{#ignored '.(count($ignored) - 1).'}';
 			}, $template);
+			// Handle {#include path/to/file}
+			$output = preg_replace_callback(static::$regex['include'], function($matches) use(&$ignored){
+				$path = static::$basedir.'/'.$matches[1];
+				if(file_exists($path)){
+					return preg_replace_callback(static::$regex['ignore'], function($matches) use(&$ignored){
+						$ignored[] = $matches[1];
+						return '{#ignored '.(count($ignored) - 1).'}';
+					}, file_get_contents($path));
+				}
+				return '';
+			}, $output);
 			// Handle {#each name}{/each}
 			$output = preg_replace_callback(static::$regex['each'], function($matches){
 				$output = "<?php if(isset(\$data[".var_export($matches[1], true)."])): ";
@@ -138,6 +151,17 @@
 				$ignored[] = $matches[1];
 				return '{#ignored '.(count($ignored) - 1).'}';
 			}, $template);
+			// Handle {#include path/to/file}
+			$output = preg_replace_callback(static::$regex['include'], function($matches) use(&$ignored){
+				$path = static::$basedir.'/'.$matches[1];
+				if(file_exists($path)){
+					return preg_replace_callback(static::$regex['ignore'], function($matches) use(&$ignored){
+						$ignored[] = $matches[1];
+						return '{#ignored '.(count($ignored) - 1).'}';
+					}, file_get_contents($path));
+				}
+				return '';
+			}, $output);
 			// Handle {#each name}{/each}
 			$output = preg_replace_callback(static::$regex['each'], function($matches) use($data){
 				$output = '';