9

How do I check to see if a particular value has already been assigned to Smarty and if not assign a (default) value?

Answer:

if ($this->cismarty->get_template_vars('test') === null) {
   $this->cismarty->assign('test', 'Default value');
}
GloryFish
  • 13,078
  • 16
  • 53
  • 43

3 Answers3

16

Smarty 2

if ($smarty->get_template_vars('foo') === null) 
{
   $smarty->assign('foo', 'some value');
}

Smarty 3

if ($smarty->getTemplateVars('foo') === null) 
{
   $smarty->assign('foo', 'some value');
}

Note that for Smarty 3, you will have to use $smarty->getTemplateVars instead.

Toby Allen
  • 10,997
  • 11
  • 73
  • 124
Andy
  • 681
  • 4
  • 7
  • Won't that just check to see it the value is not null? What if null is the proper assignment? – Allain Lalonde Dec 08 '08 at 17:13
  • In this case the behavior should be, "if a value is not set (null) then set a default value." Also, isset() connot be used to check the return value of a function, however you can just check the value itself. Thanks Andy. – GloryFish Dec 08 '08 at 17:18
  • get_template_vars() is designed to return NULL on non-existent variables. – Andy Dec 08 '08 at 17:21
  • I'm not sure that is correct, get_template_vars will always return a valid reference so you can't check with isset() – Tom Haigh Dec 08 '08 at 17:29
  • But how about in the `.tpl` file? – qg_java_17137 Jul 20 '18 at 06:40
1

get_template_vars() will return null if you haven't set a variable, so you can do

if ($smarty->get_template_vars('test') === null) {
    echo "'test' is not assigned or is null";
}

However that check will fail if you have a variable assigned but set as null, in which case you could do

$tmp = $smarty->get_template_vars();
if (!array_key_exists('test', $tmp)) {
    echo "'test' is not assigned";
}
Tom Haigh
  • 57,217
  • 21
  • 114
  • 142
0

Pretty sure you can do:

if (!isset($smarty['foo'])) 
{
    $smarty->assign('foo', 'some value');
}
Allain Lalonde
  • 91,574
  • 70
  • 187
  • 238