creates a template object
public createTemplate ( string $template, mixed $cache_id = null, mixed $compile_id = null, object $parent = null, boolean $do_clone = true ) : object | ||
$template | string | the resource handle of the template file |
$cache_id | mixed | cache id to be used with this template |
$compile_id | mixed | compile id to be used with this template |
$parent | object | next higher level of Smarty variables |
$do_clone | boolean | flag is Smarty object shall be cloned |
return | object | template object |
/** * Get the evaluated contents of the view. * * @param string $path * @param array $data * @return string */ public function get($path, array $data = array()) { $template = $this->smarty->createTemplate($path); $template->assign($this->smarty->getTemplateVars()); $template->assign($data); return $template->fetch(); }
public function render($name, array $values = array()) { if (defined('ENV_DEV')) { //$this->engine->clearCacheFiles(); //$this->engine->clearTemplateCache(); $this->engine->clearAllCache(); $this->engine->clearCompiledTemplate(); } $template = $this->engine->createTemplate($name . $this->suffix); $template->assign($values); return $template->fetch(); }
/** * test if cache is valid * * @param string|object $template the resource handle of the template file or template object * @param mixed $cache_id cache id to be used with this template * @param mixed $compile_id compile id to be used with this template * @param object $parent next higher level of Smarty variables * * @return boolean cache status */ public function isCached($template = null, $cache_id = null, $compile_id = null, $parent = null) { if ($template === null && $this instanceof $this->template_class) { return $this->cached->valid; } if (!$template instanceof $this->template_class) { if ($parent === null) { $parent = $this; } $template = $this->smarty->createTemplate($template, $cache_id, $compile_id, $parent, false); } // return cache status of template return $template->cached->valid; }
public function setUp() { $smarty = new Smarty(); $render = new CM_Frontend_Render(); $this->_template = $smarty->createTemplate('string:'); $this->_template->assignGlobal('render', $render); }
/** * Inspect the supplied source, capture gettext references as a PoFile object. * * @param string $source php source code * @param string $refname source identification used for PO reference comments * * @return PoFile */ public function msginitString($source, $refname) { if (!$this->poFile instanceof PoFile) { $this->poFile = new PoFile(); } $tpl = $this->smarty->createTemplate('eval:' . $source); $tags = $this->smarty->getTags($tpl); $translateTags = array_merge($this->gettextTags, $this->pgettextTags, $this->ngettextTags); foreach ($tags as $tag) { if (in_array($tag[0], $translateTags)) { $entry = new PoEntry(); $haveEntry = false; $entry->add(PoTokens::REFERENCE, $refname); foreach ($tag[1] as $temp) { foreach ($temp as $key => $value) { if ($value[0] == "'" || $value[0] == '"') { if (in_array($key, $this->msgidArgNames)) { $entry->set(PoTokens::MESSAGE, $this->escapeForPo($value)); $haveEntry = true; } elseif (in_array($key, $this->msgidPluralArgNames)) { $entry->set(PoTokens::PLURAL, $this->escapeForPo($value)); } elseif (in_array($key, $this->msgctxtArgNames)) { $entry->set(PoTokens::CONTEXT, $this->escapeForPo($value)); } } } } if ($haveEntry) { $this->checkPhpFormatFlag($entry); $this->poFile->mergeEntry($entry); } } } return $this->poFile; }
public function setUp() { $smarty = new Smarty(); $render = new CM_Frontend_Render(); $this->_template = $smarty->createTemplate('string:'); $this->_template->assignGlobal('render', $render); $this->_menuData = [['label' => 'Label 1', 'page' => 'CM_Page_Example', 'params' => ['foo' => 1]], ['label' => 'Label 2', 'page' => 'CM_Page_Example', 'params' => ['foo' => 2]]]; }
public function testRender() { $smarty = new Smarty(); $render = new CM_Frontend_Render(); $template = $smarty->createTemplate('string:'); $template->assignGlobal('render', $render); $this->assertSame($render->getUrlResource('layout', 'foo'), smarty_function_resourceUrl(array('path' => 'foo', 'type' => 'layout'), $template)); $this->assertSame($render->getUrlStatic('foo'), smarty_function_resourceUrl(array('path' => 'foo', 'type' => 'static'), $template)); }
public function testBackgroundImageData() { $smarty = new Smarty(); $render = new CM_Frontend_Render(); $template = $smarty->createTemplate('string:'); $template->assignGlobal('render', $render); $html = '<img src="https://example.com/img/foo.png" style="background-image: url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)" class="background-cover" width="456" height="123" />'; $this->assertSame($html, smarty_function_img(['path' => 'https://example.com/img/foo.png', 'width' => 456, 'height' => 123, 'background-image' => 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'], $template)); }
/** * @param array $params * @return CM_Dom_NodeList */ private function _createSelect(array $params) { $smarty = new Smarty(); $render = new CM_Frontend_Render(); $template = $smarty->createTemplate('string:'); $template->assignGlobal('render', $render); $html = smarty_function_select($params, $template); return new CM_Dom_NodeList($html); }
/** * Compile all template files * * @param string $extension template file name extension * @param bool $force_compile force all to recompile * @param int $time_limit set maximum execution time * @param int $max_errors set maximum allowed errors * @param Smarty $smarty Smarty instance * * @return integer number of template files compiled */ public static function compileAllTemplates($extension, $force_compile, $time_limit, $max_errors, Smarty $smarty) { // switch off time limit if (function_exists('set_time_limit')) { @set_time_limit($time_limit); } $smarty->force_compile = $force_compile; $_count = 0; $_error_count = 0; // loop over array of template directories foreach ($smarty->getTemplateDir() as $_dir) { $_compileDirs = new RecursiveDirectoryIterator($_dir); $_compile = new RecursiveIteratorIterator($_compileDirs); foreach ($_compile as $_fileinfo) { $_file = $_fileinfo->getFilename(); if (substr(basename($_fileinfo->getPathname()), 0, 1) == '.' || strpos($_file, '.svn') !== false) { continue; } if (!substr_compare($_file, $extension, -strlen($extension)) == 0) { continue; } if ($_fileinfo->getPath() == substr($_dir, 0, -1)) { $_template_file = $_file; } else { $_template_file = substr($_fileinfo->getPath(), strlen($_dir)) . DS . $_file; } echo '<br>', $_dir, '---', $_template_file; flush(); $_start_time = microtime(true); try { $_tpl = $smarty->createTemplate($_template_file, null, null, null, false); if ($_tpl->mustCompile()) { $_tpl->compileTemplateSource(); $_count++; echo ' compiled in ', microtime(true) - $_start_time, ' seconds'; flush(); } else { echo ' is up to date'; flush(); } } catch (Exception $e) { echo 'Error: ', $e->getMessage(), "<br><br>"; $_error_count++; } // free memory $smarty->template_objects = array(); $_tpl->smarty->template_objects = array(); $_tpl = null; if ($max_errors !== null && $_error_count == $max_errors) { echo '<br><br>too many errors'; exit; } } } return $_count; }
public function testRender() { $smarty = new Smarty(); $render = new CM_Frontend_Render(); $template = $smarty->createTemplate('string:'); $template->assignGlobal('render', $render); $contentExpected = $render->getLayoutFile('resource/img/favicon.svg')->read(); $contentActual = smarty_function_resourceFileContent(array('path' => 'img/favicon.svg'), $template); $this->assertGreaterThan(0, strlen($contentActual)); $this->assertSame($contentExpected, $contentActual); }
public function testRenderCrossSite() { $smarty = new Smarty(); $render = new CM_Frontend_Render(); $siteOther = $this->getMockSite('CM_Site_Abstract', null, ['urlCdn' => 'http://cdn.other.com']); $renderOther = new CM_Frontend_Render(new CM_Frontend_Environment($siteOther)); $template = $smarty->createTemplate('string:'); $template->assignGlobal('render', $render); $this->assertSame($renderOther->getUrlResource('layout', 'foo'), smarty_function_resourceUrl(array('path' => 'foo', 'type' => 'layout', 'site' => $siteOther), $template)); $this->assertSame($renderOther->getUrlStatic('foo'), smarty_function_resourceUrl(array('path' => 'foo', 'type' => 'static', 'site' => $siteOther), $template)); }
public function setUp() { $smarty = new Smarty(); $this->_render = new CM_Frontend_Render(); $this->_template = $smarty->createTemplate('string:'); $this->_template->assignGlobal('render', $this->_render); $language = CMTest_TH::createLanguage(); $language->setTranslation('.date.period.years', '{$count} years', ['count']); $language->setTranslation('.date.period.hour', '1 hour'); $language->setTranslation('.date.period.day', '1 day'); }
public function setUp() { $smarty = new Smarty(); $render = new CM_Frontend_Render(); $formMock = $this->getMockForAbstractClass('CM_Form_Abstract', array(), '', true, true, true, array('getAction')); $actionMock = $this->getMockForAbstractClass('CM_FormAction_Abstract', array($formMock), '', true, true, true, array('getName')); $actionMock->expects($this->any())->method('getName')->will($this->returnValue('Create')); $formMock->expects($this->any())->method('getAction')->will($this->returnValue($actionMock)); /** @var CM_Form_Abstract $formMock */ $render->getGlobalResponse()->treeExpand(new CM_Frontend_ViewResponse($formMock)); $this->_template = $smarty->createTemplate('string:'); $this->_template->assignGlobal('render', $render); }
public function testRender() { $smarty = new Smarty(); $template = $smarty->createTemplate('string:'); $this->assertContainsAll(['div', 'data-foo="3"', 'data-bar="baz"', 'foo bar'], smarty_function_tag(['el' => 'div', 'content' => 'foo bar', 'data' => ['foo' => 3, 'bar' => 'baz']], $template)); $exception = $this->catchException(function () use($template) { smarty_function_tag(['content' => 'foo bar'], $template); }); $this->assertInstanceOf('ErrorException', $exception); $this->assertContains('Param `el` missing.', $exception->getMessage()); $exception = $this->catchException(function () use($template) { smarty_function_tag(['el' => 'span', 'data' => 'foo bar'], $template); }); $this->assertInstanceOf('ErrorException', $exception); $this->assertContains('Param `data` should be an array.', $exception->getMessage()); }
/** * Creates a template object * * @param string $template the resource handle of the template file * @param mixed $cache_id cache id to be used with this template * @param mixed $compile_id compile id to be used with this template * @param object $parent next higher level of Smarty variables * @param boolean $do_clone flag is Smarty object shall be cloned * @return object template object */ public function createTemplate($template, $cache_id = null, $compile_id = null, $parent = null, $do_clone = false) { return parent::createTemplate($template, $cache_id, $compile_id, $parent, $do_clone); }
/** * Delete compiled template file * * @api Smarty::clearCompiledTemplate() * @link http://www.smarty.net/docs/en/api.clear.compiled.template.tpl * * @param \Smarty $smarty * @param string $resource_name template name * @param string $compile_id compile id * @param integer $exp_time expiration time * * @return integer number of template files deleted */ public function clearCompiledTemplate(Smarty $smarty, $resource_name = null, $compile_id = null, $exp_time = null) { // clear template objects cache $smarty->_clearTemplateCache(); $_compile_dir = $smarty->getCompileDir(); if ($_compile_dir == '/') { //We should never want to delete this! return 0; } $_compile_id = isset($compile_id) ? preg_replace('![^\\w]+!', '_', $compile_id) : null; $_dir_sep = $smarty->use_sub_dirs ? $smarty->ds : '^'; if (isset($resource_name)) { $_save_stat = $smarty->caching; $smarty->caching = false; /* @var Smarty_Internal_Template $tpl */ $tpl = $smarty->createTemplate($resource_name); $smarty->caching = $_save_stat; if (!$tpl->source->handler->uncompiled && !$tpl->source->handler->recompiled && $tpl->source->exists) { $_resource_part_1 = basename(str_replace('^', $smarty->ds, $tpl->compiled->filepath)); $_resource_part_1_length = strlen($_resource_part_1); } else { return 0; } $_resource_part_2 = str_replace('.php', '.cache.php', $_resource_part_1); $_resource_part_2_length = strlen($_resource_part_2); } $_dir = $_compile_dir; if ($smarty->use_sub_dirs && isset($_compile_id)) { $_dir .= $_compile_id . $_dir_sep; } if (isset($_compile_id)) { $_compile_id_part = $_compile_dir . $_compile_id . $_dir_sep; $_compile_id_part_length = strlen($_compile_id_part); } $_count = 0; try { $_compileDirs = new RecursiveDirectoryIterator($_dir); // NOTE: UnexpectedValueException thrown for PHP >= 5.3 } catch (Exception $e) { return 0; } $_compile = new RecursiveIteratorIterator($_compileDirs, RecursiveIteratorIterator::CHILD_FIRST); foreach ($_compile as $_file) { if (substr(basename($_file->getPathname()), 0, 1) == '.') { continue; } $_filepath = (string) $_file; if ($_file->isDir()) { if (!$_compile->isDot()) { // delete folder if empty @rmdir($_file->getPathname()); } } else { // delete only php files if (substr($_filepath, -4) !== '.php') { continue; } $unlink = false; if ((!isset($_compile_id) || isset($_filepath[$_compile_id_part_length]) && ($a = !strncmp($_filepath, $_compile_id_part, $_compile_id_part_length))) && (!isset($resource_name) || isset($_filepath[$_resource_part_1_length]) && substr_compare($_filepath, $_resource_part_1, -$_resource_part_1_length, $_resource_part_1_length) == 0 || isset($_filepath[$_resource_part_2_length]) && substr_compare($_filepath, $_resource_part_2, -$_resource_part_2_length, $_resource_part_2_length) == 0)) { if (isset($exp_time)) { if (time() - @filemtime($_filepath) >= $exp_time) { $unlink = true; } } else { $unlink = true; } } if ($unlink && @unlink($_filepath)) { $_count++; if (function_exists('opcache_invalidate') && strlen(ini_get("opcache.restrict_api")) < 1) { opcache_invalidate($_filepath, true); } } } } return $_count; }
/** * {@inheritDoc} */ public function createTemplate($template, $cache_id = null, $compile_id = null, $parent = null, $do_clone = true) { $this->check_compile_cache_invalidation(); if ($this->caching) { $this->check_template_invalidation($template, $cache_id, $compile_id); return parent::createTemplate($template, $cache_id, $compile_id, $parent, $do_clone); } else { return parent::createTemplate($template, $cache_id, $compile_id, $parent, $do_clone); } }
/** * Renders the template. * * This displays the contents of a template. To return the contents of a * template into a variable, use the fetch() method instead. * * As an optional second and third parameter, you can pass a cache ID and * compile ID. * * A fourth parameter can be passed which passes the parent scope that the * template should use. * * @param string|null|void $template the resource handle of the template file or template object * @param string|null|void $compile_id compile id to be used with this template * @return void */ public function display($template = null, $compile_id = null) { if ($template === null && $this instanceof Template) { $template = $this; } // create template object if necessary if (!$template instanceof Template) { $template = $this->smarty->createTemplate($template, $compile_id, $this); } // Add the smarty variable, if needed. // We check is_array() because tpl_vars might be an OverlayScope, which // will always have its parent's smarty variable. if (is_array($template->tpl_vars) && !isset($template->tpl_vars['smarty'])) { $template->tpl_vars['smarty'] = array('blocks' => array(), 'functions' => array(), 'foreach' => array(), 'ls_loadables' => array()); } if (!empty(Brainy::$global_tpl_vars)) { foreach (Brainy::$global_tpl_vars as $key => $value) { $template->tpl_vars[$key] =& $value; } } // get rendered template // checks if template exists if (!$template->source->exists) { $parent_resource = ''; if ($template->parent instanceof Template) { $parent_resource = " in '{$template->parent->template_resource}'"; } throw new SmartyException("Unable to load template {$template->source->type} '{$template->source->name}'{$parent_resource}"); } $_smarty_tpl = $template; // read from cache or render if ($template->source->recompiled) { // recompiled === 'eval' $code = $template->compileTemplateSource(); eval('?>' . $code); // The closing PHP bit accounts for the opening PHP tag at the top of the compiled file unset($code); } else { if (!$template->compiled->exists || $template->smarty->force_compile && !$template->compiled->isCompiled) { $template->compileTemplateSource(); } if (!$template->compiled->loaded) { $template->compiled->load($template); // If the template source's timestamp is greater than that of // the timestamp on its stored dependency, we will not be able // to decode the properties of the compiled template. Thus the // template needs to be recompiled here. if (empty($template->properties['unifunc']) || !is_callable($template->properties['unifunc'])) { $template->recompileAndLoadCopy(); } } else { $template->decodeProperties($template->compiled->properties, false); } if (empty($template->properties['unifunc']) || !is_callable($template->properties['unifunc'])) { throw new SmartyException("Invalid compiled template for '{$template->template_resource}': no unifunc found"); } // render compiled template call_user_func($template->properties['unifunc'], $template); } if (!$template->source->recompiled && empty($template->properties['file_dependency'][$template->source->uid])) { $template->properties['file_dependency'][$template->source->uid] = array($template->source->filepath, $template->source->timestamp, $template->source->type); } if ($template->parent instanceof Template) { $template->parent->properties['file_dependency'] = array_merge($template->parent->properties['file_dependency'], $template->properties['file_dependency']); foreach ($template->required_plugins as $code => $tmp1) { foreach ($tmp1 as $name => $tmp) { foreach ($tmp as $type => $data) { $template->parent->required_plugins[$code][$name][$type] = $data; } } } } }
public function setUp() { $smarty = new Smarty(); $this->_template = $smarty->createTemplate('string:'); }
/** * Ejecuta una peticion * * Carga el componente y ejecuta su metodo especifico * Si $mostrar tiene un valor true, se invoca la plantilla respectiva * y se muestra el contenido. Si tiene un valor false, ejecuta el metodo del modulo * invocado y retorna su respuesta * * @param String $peticion * @param Boolean $mostrar * @return unknown */ public function ejecutar($peticion, $parametros = null, $mostrar = true, $llamado = false) { //Separara la peticion en Componente y accion $peticion = explode(".", $peticion); $componente = $peticion[0]; $accion = $peticion[1]; $dir = strtolower($componente); //Verifica la existencia del componente y lo incluye o devuelve un error if (file_exists("app/componentes/{$dir}.class.php")) { require_once "app/componentes/{$dir}.class.php"; //Crear el objeto de datos smarty independiente para el componente $c_smarty = new Smarty_Data($this->smarty); $obj = new $componente($this, $c_smarty, $parametros, $llamado); //Verifica la exitencia de la accion o devuelve un error if (method_exists($obj, $accion)) { if ($mostrar) { //$this->smarty->assign("componente", $dir); //$this->smarty->assign("vista", $accion); //Se asignan las variables al smarty personal del componente $c_smarty->assign("componente", $dir); $c_smarty->assign("vista", $accion); //ejecuta la accion del componente $obj->{$accion}(); //Verifica la bandera Ajax, si es afirmativa muestra una vista if ($this->parametros['ajaxafw'] == 1 && $obj->ajax == "" || $obj->ajax == 1) { //$this->smarty->assign("ajaxafw", 1); $c_smarty->assign("ajaxafw", 1); //Obtiene la vista a incluir //$ptl=$this->smarty->get_template_vars("vista"); //$mod=$this->smarty->get_template_vars("componente"); $ptl = $c_smarty->getTemplateVars("vista"); $mod = $c_smarty->getTemplateVars("componente"); //Verifica la existencia de la vista y la muestra if (file_exists("app/vistas/{$mod}/{$ptl}.tpl")) { //$this->smarty->display("mostrar.tpl"); $tpl = $this->smarty->createTemplate("mostrar.tpl", $c_smarty); $tpl->display(); } else { Error::manejarError($this, 3, array($ptl . ".tpl", $componente, $accion)); return; } } else { //En el caso contrario de no ser una peticion ajax, llama a la plantilla seleccionada //Y la muestra $ini = new Configuracion(); $plantilla = $ini->get("plantilla", "default"); //Si se ha definido una plantilla diferente para el modulo se usa if ($obj->plantilla != null) { $plantilla = $obj->plantilla; } //obtiene la vista a incluir //$ptl=$this->smarty->get_template_vars("vista"); //$mod=$this->smarty->get_template_vars("componente"); $ptl = $c_smarty->getTemplateVars("vista"); $mod = $c_smarty->getTemplateVars("componente"); //Verifica la existencia de la vista y la plantilla y procede a mostrarla if (file_exists("app/vistas/{$mod}/{$ptl}.tpl")) { //$this->smarty->assign("vista", "$ptl"); $c_smarty->assign("vista", "{$ptl}"); if (file_exists("app/vistas/plantillas/{$plantilla}.tpl")) { //$this->smarty->display("plantillas/$plantilla.tpl"); $tpl = $this->smarty->createTemplate("plantillas/{$plantilla}.tpl", $c_smarty); $tpl->display(); } else { Error::manejarError($this, 4, array($plantilla, $ptl . ".tpl", $componente, $accion)); } } else { Error::manejarError($this, 3, array($ptl . ".tpl", $componente, $accion)); return; } } } else { return $obj->{$accion}(); } } else { Error::manejarError($this, 2, array($componente, $accion)); return; } } else { Error::manejarError($this, 1, $componente); return; } }