X-Git-Url: https://vcs.fsf.org/?a=blobdiff_plain;f=CRM%2FCore%2FSmarty.php;h=f683c56574a3767edbe1dc3839825e18767ecf2c;hb=bcec4b421ba045a45e8ca4394100824698ca7905;hp=a29d2e231f238c616233fb98e5ce4a991f37c9da;hpb=58a50b22e20f112fdbfc7e50f18353c311ceb1ae;p=civicrm-core.git diff --git a/CRM/Core/Smarty.php b/CRM/Core/Smarty.php index a29d2e231f..f683c56574 100644 --- a/CRM/Core/Smarty.php +++ b/CRM/Core/Smarty.php @@ -73,6 +73,11 @@ class CRM_Core_Smarty extends Smarty { */ static private $_singleton = NULL; + /** + * @var array (string $name => mixed $value) a list of variables ot save temporarily + */ + private $backupFrames = array(); + /** * class constructor * @@ -204,6 +209,27 @@ class CRM_Core_Smarty extends Smarty { return $output; } + /** + * Fetch a template (while using certain variables) + * + * @param string $resource_name + * @param array $vars (string $name => mixed $value) variables to export to Smarty + * @throws Exception + * @return bool|mixed|string + */ + function fetchWith($resource_name, $vars) { + $this->pushScope($vars); + try { + $result = $this->fetch($resource_name); + } catch (Exception $e) { + // simulate try { ... } finally { ... } + $this->popScope(); + throw $e; + } + $this->popScope(); + return $result; + } + /** * @param $name * @param $value @@ -245,5 +271,56 @@ class CRM_Core_Smarty extends Smarty { } } + + /** + * Temporarily assign a list of variables. + * + * @code + * $smarty->pushScope(array( + * 'first_name' => 'Alice', + * 'last_name' => 'roberts', + * )); + * $html = $smarty->fetch('view-contact.tpl'); + * $smarty->popScope(); + * @endcode + * + * @param array $vars (string $name => mixed $value) + * @return CRM_Core_Smarty + * @see popScope + */ + public function pushScope($vars) { + $oldVars = $this->get_template_vars(); + $backupFrame = array(); + foreach ($vars as $key => $value) { + $backupFrame[$key] = isset($oldVars[$key]) ? $oldVars[$key] : NULL; + } + $this->backupFrames[] = $backupFrame; + + $this->assignAll($vars); + + return $this; + } + + /** + * Remove any values that were previously pushed. + * + * @return CRM_Core_Smarty + * @see pushScope + */ + public function popScope() { + $this->assignAll(array_pop($this->backupFrames)); + return $this; + } + + /** + * @param array $vars (string $name => mixed $value) + * @return CRM_Core_Smarty + */ + public function assignAll($vars) { + foreach ($vars as $key => $value) { + $this->assign($key, $value); + } + return $this; + } }