pquery.template.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /**
  3. * pQuery plugin for parsing templates.
  4. *
  5. * @package pQuery
  6. */
  7. /**
  8. * @todo Documentation
  9. * @property $ Alias for {@link pQuery::variable}.
  10. */
  11. class pQueryTemplate extends pQuery implements pQueryExtension {
  12. static $accepts = array('string' => 'open_template_file');
  13. /**
  14. * Root folders from which template files will be included.
  15. *
  16. * @var string
  17. */
  18. static $include_path = array();
  19. /**
  20. * @see pQuery::$variable_alias
  21. * @var string|array
  22. */
  23. static $variable_alias = 'template';
  24. /**
  25. * Open the given template filename in the current variable.
  26. */
  27. function open_template_file() {
  28. $found = false;
  29. foreach( self::$include_path as $root ) {
  30. $path = $root.$this->variable;
  31. if( is_file($path) ) {
  32. $found = true;
  33. break;
  34. }
  35. }
  36. if( !$found ) {
  37. return self::error("Could not find template file \"%s\", looked in folders:\n%s",
  38. $this->variable, implode("\n", self::$include_path));
  39. }
  40. $this->content = file_get_contents($path);
  41. }
  42. /**
  43. * Replace all include paths by a single new one.
  44. *
  45. * @param str $path The path to set.
  46. * @param bool $relative Indicates whether the path is relative to the document root.
  47. */
  48. static function set_root($path, $relative=true) {
  49. self::$include_path = array();
  50. self::add_root($path);
  51. }
  52. /**
  53. * Add a new include path.
  54. *
  55. * @param str $path The path to add.
  56. * @param bool $relative Indicates whether the path is relative to the document root.
  57. */
  58. static function add_root($path, $relative=true) {
  59. $relative && $path = PQUERY_ROOT.$path;
  60. preg_match('%/$%', $path) || $path .= '/';
  61. if( !is_dir($path) )
  62. return self::error('"%s" is not a directory.', $path);
  63. self::$include_path[] = $path;
  64. }
  65. }
  66. /**
  67. * Shortcut constructor for {@link pQueryTemplate}.
  68. *
  69. * @param string $path The path to a template file.
  70. * @returns pQueryTemplate A new template instance.
  71. */
  72. function _tpl($path) {
  73. return pQuery::create('tpl', $path);
  74. }
  75. __p::extend('pQueryTemplate', 'tpl');
  76. __tpl::set_root('');
  77. ?>